[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
} else {
$isIp = (bool) ip2long($pieces['host']);
if ($isIp) {
return $pieces['host'];
}
}
return false;
}
function siteMap() {
_error_log("siteMap: start");
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
global $global, $advancedCustom;
$date = date('Y-m-d\TH:i:s') . "+00:00";
$xml = '
' . $global['webSiteRootURL'] . '
' . $date . '
always
1.00
' . $global['webSiteRootURL'] . 'help
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'about
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'contact
' . $date . '
monthly
0.50
' . $global['webSiteRootURL'] . 'channels
' . $date . '
daily
0.80
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
_error_log("siteMap: rowCount {$_REQUEST['rowCount']} ");
$_POST['sort']['modified'] = "DESC";
$users = User::getAllUsersThatHasVideos(true);
_error_log("siteMap: getAllUsers " . count($users));
foreach ($users as $value) {
$xml .= '
' . User::getChannelLink($value['id']) . '
' . $date . '
daily
0.90
';
}
$xml .= '
';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit;
$_POST['sort']['modified'] = "DESC";
$rows = Category::getAllCategories();
_error_log("siteMap: getAllCategories " . count($rows));
foreach ($rows as $value) {
$xml .= '
' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . '
' . $date . '
weekly
0.80
';
}
$xml .= '';
$_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10;
$_POST['sort']['created'] = "DESC";
$rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly");
_error_log("siteMap: getAllVideos " . count($rows));
foreach ($rows as $video) {
$videos_id = $video['id'];
//_error_log("siteMap: getAllVideos videos_id {$videos_id} start");
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = getCDN() . "view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = parseDurationToSeconds($video['duration']);
if ($duration > 28800) {
// this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore
$duration = 28800;
}
$xml .= '
' . Video::getLink($video['id'], $video['clean_title']) . '
' . $img . '
' . $duration . '
' . $video['views_count'] . '
' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00
yes
' . (Video::isPublic($video['id']) ? "no" : "yes") . '
' . User::getNameIdentificationById($video['users_id']) . '
no
';
}
$xml .= ' ';
_error_log("siteMap: done ");
$newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml);
if (empty($newXML1)) {
_error_log("siteMap: pregreplace1 fail ");
$newXML1 = $xml;
}
if (!empty($advancedCustom->siteMapUTF8Fix)) {
$newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1);
if (empty($newXML2)) {
_error_log("siteMap: pregreplace2 fail ");
$newXML2 = $newXML1;
}
$newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2);
if (empty($newXML3)) {
_error_log("siteMap: pregreplace3 fail ");
$newXML3 = $newXML2;
}
$newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3);
if (empty($newXML4)) {
_error_log("siteMap: pregreplace4 fail ");
$newXML4 = $newXML3;
}
$newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4);
if (empty($newXML5)) {
_error_log("siteMap: pregreplace5 fail ");
$newXML5 = $newXML4;
}
} else {
$newXML5 = $newXML1;
}
return $newXML5;
}
function object_to_array($obj) {
//only process if it's an object or array being passed to the function
if (is_object($obj) || is_array($obj)) {
$ret = (array) $obj;
foreach ($ret as &$item) {
//recursively process EACH element regardless of type
$item = object_to_array($item);
}
return $ret;
}
//otherwise (i.e. for scalar values) return without modification
else {
return $obj;
}
}
function allowOrigin() {
global $global;
if (empty($_SERVER['HTTP_ORIGIN'])) {
$server = parse_url($global['webSiteRootURL']);
header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com');
} else {
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
}
function rrmdir($dir) {
if (empty($dir)) {
_error_log('rrmdir: the dir was empty');
return false;
}
global $global;
$dir = fixPath($dir, true);
$pattern = '/' . addcslashes($dir, DIRECTORY_SEPARATOR) . 'videos[\/\\\]?$/i';
if ($dir == getVideosDir() || $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR || preg_match($pattern, $dir)) {
_error_log('rrmdir: A script ties to delete the videos Directory [' . $dir . '] ' . json_encode(array($dir == getVideosDir(), $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR, preg_match($pattern, $dir))));
return false;
}
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir . "/" . $object)) {
rrmdir($dir . "/" . $object);
} else {
@unlink($dir . "/" . $object);
}
}
}
@rmdir($dir);
if (is_dir($dir)) {
_error_log('rrmdir: The Directory was not deleted, trying again ' . $dir);
exec('rm -R ' . $dir);
}
} else {
//_error_log('rrmdir: The Directory does not exists '.$dir);
}
}
/**
* You can now configure it on the configuration.php
* @return boolean
*/
function ddosProtection() {
global $global;
$maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections'];
$secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout'];
$whitelistedFiles = array(
'playlists.json.php',
'playlistsFromUserVideos.json.php',
'image404.php'
);
if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) {
return true;
}
$time = time();
if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) {
$_SESSION['bruteForceBlock'] = array();
$_SESSION['bruteForceBlock'][] = $time;
return true;
}
$_SESSION['bruteForceBlock'][] = $time;
//remove requests that are older than secondTimeout
foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) {
if ($request_time < $time - $secondTimeout) {
unset($_SESSION['bruteForceBlock'][$key]);
}
}
//progressive timeout-> more requests, longer timeout
$active_connections = count($_SESSION['bruteForceBlock']);
$timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout;
if ($timeoutReal) {
_error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY);
}
sleep($timeoutReal);
//with strict mode, penalize "attacker" with sleep() above, log and then die
if ($global['strictDDOSprotection'] && $timeoutReal > 0) {
$str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']);
_error_log($str);
die($str);
}
return true;
}
function getAdsLeaderBoardBigVideo() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value);
}
}
}
function getAdsLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop->value);
}
}
}
function getAdsChannelLeaderBoardTop() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value);
}
}
}
function getAdsLeaderBoardTop2() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value);
}
}
}
function getAdsLeaderBoardMiddle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value);
}
}
}
function getAdsLeaderBoardFooter() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value);
} else {
return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value);
}
}
}
function getAdsSideRectangle() {
$ad = AVideoPlugin::getObjectDataIfEnabled('ADs');
if (!empty($ad)) {
if (isMobile()) {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
} else {
return ADs::giveGoogleATimeout($ad->sideRectangle->value);
}
}
}
function isToHidePrivateVideos() {
$obj = AVideoPlugin::getObjectDataIfEnabled("Gallery");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
$obj = AVideoPlugin::getObjectDataIfEnabled("YouTube");
if (!empty($obj)) {
return $obj->hidePrivateVideos;
}
return false;
}
function convertImageToOG($source, $destination) {
if (!file_exists($destination)) {
$w = 200;
$h = 200;
$sizes = getimagesize($source);
if ($sizes[0] < $w || $sizes[1] < $h) {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
unlink($fileConverted);
}
}
return $destination;
}
function convertImageToRoku($source, $destination) {
if (empty($source)) {
_error_log("convertImageToRoku: source image is empty");
return false;
}
$w = 1280;
$h = 720;
if (file_exists($destination)) {
$sizes = getimagesize($destination);
if ($sizes[0] < $w || $sizes[1] < $h) {
_error_log("convertImageToRoku: file is smaller " . json_encode($sizes));
unlink($destination);
}
}
if (!file_exists($destination)) {
try {
$tmpDir = getTmpDir();
$fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg";
convertImage($source, $fileConverted, 100);
im_resizeV2($fileConverted, $destination, $w, $h, 100);
@unlink($fileConverted);
} catch (Exception $exc) {
_error_log("convertImageToRoku: " . $exc->getMessage());
return false;
}
}
return $destination;
}
function ogSite() {
global $global, $config;
include $global['systemRootPath'] . 'objects/functionogSite.php';
}
function getOpenGraph($videos_id) {
global $global, $config, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php';
}
function getLdJson($videos_id) {
$cache = ObjectYPT::getCache("getLdJson{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = getCDN() . "view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getLdJson{$videos_id}", $output);
echo $output;
}
function getItemprop($videos_id) {
$cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0);
if (empty($cache)) {
echo $cache;
}
global $global, $config;
echo "";
if (empty($videos_id)) {
echo "";
if (!empty($_GET['videoName'])) {
echo "";
$video = Video::getVideoFromCleanTitle($_GET['videoName']);
}
} else {
echo "";
$video = Video::getVideoLight($videos_id);
}
if (empty($video)) {
echo "";
return false;
}
$videos_id = $video['id'];
$source = Video::getSourceFile($video['filename']);
if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) {
$img = $source['url'];
$data = getimgsize($source['path']);
$imgw = $data[0];
$imgh = $data[1];
} elseif ($video['type'] == "audio") {
$img = getCDN() . "view/img/audio_wave.jpg";
}
$type = 'video';
if ($video['type'] === 'pdf') {
$type = 'pdf';
}
if ($video['type'] === 'image') {
$type = 'image';
}
if ($video['type'] === 'zip') {
$type = 'zip';
}
if ($video['type'] === 'article') {
$type = 'article';
}
$images = Video::getImageFromFilename($video['filename'], $type);
if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') {
$img = $images->posterPortrait;
$data = getimgsize($images->posterPortraitPath);
$imgw = $data[0];
$imgh = $data[1];
} else {
$img = $images->poster;
}
$description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']);
$duration = Video::getItemPropDuration($video['duration']);
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
$output = '
';
ObjectYPT::setCache("getItemprop{$videos_id}", $output);
echo $output;
}
function getOS($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
function get_browser_name($user_agent = "") {
if (empty($user_agent)) {
$user_agent = @$_SERVER['HTTP_USER_AGENT'];
}
if (empty($user_agent)) {
return 'Unknow';
}
// Make case insensitive.
$t = strtolower($user_agent);
// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
// "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
// http://php.net/manual/en/function.strpos.php
$t = " " . $t;
// Humans / Regular Users
if (isAVideoStreamer($t)) {
return 'AVideo Mobile App';
} elseif ($url = isAVideoEncoder($t)) {
return 'AVideo Encoder ' . $url;
} elseif ($url = isAVideoStreamer($t)) {
return 'AVideo Streamer ' . $url;
} elseif (strpos($t, 'crkey')) {
return 'Chromecast';
} elseif (strpos($t, 'opera') || strpos($t, 'opr/')) {
return 'Opera';
} elseif (strpos($t, 'edge')) {
return 'Edge';
} elseif (strpos($t, 'chrome')) {
return 'Chrome';
} elseif (strpos($t, 'safari')) {
return 'Safari';
} elseif (strpos($t, 'firefox')) {
return 'Firefox';
} elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) {
return 'Internet Explorer';
} elseif (strpos($t, 'applecoremedia')) {
return 'Native Apple Player';
}
// Search Engines
elseif (strpos($t, 'google')) {
return '[Bot] Googlebot';
} elseif (strpos($t, 'bing')) {
return '[Bot] Bingbot';
} elseif (strpos($t, 'slurp')) {
return '[Bot] Yahoo! Slurp';
} elseif (strpos($t, 'duckduckgo')) {
return '[Bot] DuckDuckBot';
} elseif (strpos($t, 'baidu')) {
return '[Bot] Baidu';
} elseif (strpos($t, 'yandex')) {
return '[Bot] Yandex';
} elseif (strpos($t, 'sogou')) {
return '[Bot] Sogou';
} elseif (strpos($t, 'exabot')) {
return '[Bot] Exabot';
} elseif (strpos($t, 'msn')) {
return '[Bot] MSN';
}
// Common Tools and Bots
elseif (strpos($t, 'mj12bot')) {
return '[Bot] Majestic';
} elseif (strpos($t, 'ahrefs')) {
return '[Bot] Ahrefs';
} elseif (strpos($t, 'semrush')) {
return '[Bot] SEMRush';
} elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) {
return '[Bot] Moz or OpenSiteExplorer';
} elseif (strpos($t, 'frog') || strpos($t, 'screaming')) {
return '[Bot] Screaming Frog';
}
// Miscellaneous
elseif (strpos($t, 'facebook')) {
return '[Bot] Facebook';
} elseif (strpos($t, 'pinterest')) {
return '[Bot] Pinterest';
}
// Check for strings commonly used in bot user agents
elseif (strpos($t, 'crawler') || strpos($t, 'api') ||
strpos($t, 'spider') || strpos($t, 'http') ||
strpos($t, 'bot') || strpos($t, 'archive') ||
strpos($t, 'info') || strpos($t, 'data')) {
return '[Bot] Other';
}
//_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI());
return 'Other (Unknown)';
}
/**
* Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7
* we need to detect the chrome browser and load an older version
*
*/
function isOldChromeVersion() {
$global;
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
if (!empty($global['forceOldChrome'])) {
return true;
}
if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) {
return version_compare($matches[1], '80', '<=');
}
return false;
}
function TimeLogStart($name) {
global $global;
if (!empty($global['noDebug'])) {
return false;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
if (empty($global['start']) || !is_array($global['start'])) {
$global['start'] = array();
}
$global['start'][$name] = $time;
}
function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) {
global $global;
if (!empty($global['noDebug']) || empty($global['start'][$name])) {
return false;
}
if (!empty($global['TimeLogLimit'])) {
$TimeLogLimit = $global['TimeLogLimit'];
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $global['start'][$name]), 4);
if (empty($global['noDebugSlowProcess']) && $total_time > $TimeLogLimit) {
_error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}");
}
TimeLogStart($name);
}
class AVideoLog {
public static $DEBUG = 0;
public static $WARNING = 1;
public static $ERROR = 2;
public static $SECURITY = 3;
public static $SOCKET = 4;
}
function _error_log_debug($message, $show_args = false) {
$array = debug_backtrace();
$message .= PHP_EOL;
foreach ($array as $value) {
$message .= "function: {$value['function']} Line: {{$value['line']}} File: {{$value['file']}}" . PHP_EOL;
if ($show_args) {
$message .= print_r($value['args'], true) . PHP_EOL;
}
}
_error_log(PHP_EOL . '***' . PHP_EOL . $message . '***');
}
function _error_log($message, $type = 0, $doNotRepeat = false) {
if (empty($doNotRepeat)) {
// do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error
$doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']);
}
if ($doNotRepeat) {
return false;
}
global $global;
if (!empty($global['noDebug']) && $type == 0) {
return false;
}
if (!is_string($message)) {
$message = json_encode($message);
}
$prefix = "AVideoLog::";
switch ($type) {
case AVideoLog::$DEBUG:
$prefix .= "DEBUG: ";
break;
case AVideoLog::$WARNING:
$prefix .= "WARNING: ";
break;
case AVideoLog::$ERROR:
$prefix .= "ERROR: ";
break;
case AVideoLog::$SECURITY:
$prefix .= "SECURITY: ";
break;
case AVideoLog::$SOCKET:
$prefix .= "SOCKET: ";
break;
}
error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}");
}
function postVariables($url, $array) {
if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) {
return false;
}
$array = object_to_array($array);
$ch = curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// execute!
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// close the connection, release resources used
curl_close($ch);
if ($httpcode == 200) {
return true;
}
return $httpcode;
}
function _session_start(array $options = array()) {
try {
if (session_status() == PHP_SESSION_NONE) {
return @session_start($options);
}
} catch (Exception $exc) {
_error_log("_session_start: " . $exc->getTraceAsString());
return false;
}
}
function _mysql_connect() {
global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort, $mysql_connect_was_closed;
try {
if (!_mysql_is_open()) {
$mysql_connect_was_closed = 0;
$global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort);
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
}
} catch (Exception $exc) {
_error_log($exc->getTraceAsString());
return false;
}
}
function _mysql_close() {
global $global, $mysql_connect_was_closed;
if (_mysql_is_open()) {
$mysql_connect_was_closed = 1;
@$global['mysqli']->close();
$global['mysqli'] = false;
}
}
function _mysql_is_open() {
global $global, $mysql_connect_was_closed;
try {
//if (is_object($global['mysqli']) && (empty($mysql_connect_was_closed) || !empty(@$global['mysqli']->ping()))) {
if (is_object($global['mysqli']) && empty($mysql_connect_was_closed)) {
return true;
}
} catch (Exception $exc) {
return false;
}
return false;
}
function remove_utf8_bom($text) {
if (strlen($text) > 1000000) {
return $text;
}
$bom = pack('H*', 'EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
function getCacheDir() {
$p = AVideoPlugin::loadPlugin("Cache");
return $p->getCacheDir();
}
function clearCache($firstPageOnly = false) {
global $global;
$dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR;
if ($firstPageOnly || !empty($_GET['FirstPage'])) {
$dir .= "firstPage" . DIRECTORY_SEPARATOR;
}
//_error_log('clearCache 1: '.$dir);
rrmdir($dir);
$dir = getCacheDir();
if ($firstPageOnly || !empty($_GET['FirstPage'])) {
$dir .= "firstPage" . DIRECTORY_SEPARATOR;
}
//_error_log('clearCache 2: '.$dir);
rrmdir($dir);
$dir = getTmpDir() . 'YPTObjectCache' . DIRECTORY_SEPARATOR;
if ($firstPageOnly || !empty($_GET['FirstPage'])) {
$dir .= "firstPage" . DIRECTORY_SEPARATOR;
}
//_error_log('clearCache 3: '.$dir);
rrmdir($dir);
ObjectYPT::deleteCache("getEncoderURL");
}
function getUsageFromFilename($filename, $dir = "") {
global $global;
if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
if (empty($dir)) {
$dir = getVideosDir() . "";
}
$pos = strrpos($dir, '/');
$dir .= (($pos === false) ? "/" : "");
$totalSize = 0;
_error_log("getUsageFromFilename: start {$dir}{$filename}");
//$files = glob("{$dir}{$filename}*");
$files = globVideosDir($filename);
session_write_close();
$filesProcessed = array();
if (empty($files)) {
_error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one");
file_put_contents("{$dir}{$filename}.notfound", time());
$totalSize = 10;
} else {
foreach ($files as $f) {
if (strpos($f, '.size.lock') !== false) {
continue;
}
if (is_dir($f)) {
_error_log("getUsageFromFilename: {$f} is Dir");
$dirSize = getDirSize($f);
$totalSize += $dirSize;
if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) {
// probably the HLS file is hosted on the YPTStorage
$info = YPTStorage::getFileInfo($filename);
if (!empty($info->size)) {
$totalSize += $info->size;
}
}
} elseif (is_file($f)) {
$filesize = filesize($f);
if ($filesize < 20) { // that means it is a dummy file
$lockFile = $f . ".size.lock";
if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) {
file_put_contents($lockFile, time());
_error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})");
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
//$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
if (!empty($aws_s3)) {
_error_log("getUsageFromFilename: Get from S3");
$filesize += $aws_s3->getFilesize($filename);
} elseif (!empty($bb_b2)) {
// TODO
} else {
$urls = Video::getVideosPaths($filename, true);
_error_log("getUsageFromFilename: Paths " . json_encode($urls));
if (!empty($urls["m3u8"]['url'])) {
$filesize += getUsageFromURL($urls["m3u8"]['url']);
}
if (!empty($urls['mp4'])) {
foreach ($urls['mp4'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls['webm'])) {
foreach ($urls['webm'] as $mp4) {
if (in_array($mp4, $filesProcessed)) {
continue;
}
$filesProcessed[] = $mp4;
$filesize += getUsageFromURL($mp4);
}
}
if (!empty($urls["pdf"]['url'])) {
$filesize += getUsageFromURL($urls["pdf"]['url']);
}
if (!empty($urls["image"]['url'])) {
$filesize += getUsageFromURL($urls["image"]['url']);
}
if (!empty($urls["zip"]['url'])) {
$filesize += getUsageFromURL($urls["zip"]['url']);
}
if (!empty($urls["mp3"]['url'])) {
$filesize += getUsageFromURL($urls["mp3"]['url']);
}
}
unlink($lockFile);
}
} else {
_error_log("getUsageFromFilename: {$f} is File ({$filesize})");
}
$totalSize += $filesize;
}
}
}
return $totalSize;
}
/**
* Returns the size of a file without downloading it, or -1 if the file
* size could not be determined.
*
* @param $url - The location of the remote file to download. Cannot
* be null or empty.
*
* @return The size of the file referenced by $url, or false if the size
* could not be determined.
*/
function getUsageFromURL($url) {
global $global;
if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage
return 0;
}
_error_log("getUsageFromURL: start ({$url})");
// Assume failure.
$result = false;
$curl = curl_init($url);
_error_log("getUsageFromURL: curl_init ");
try {
// Issue a HEAD request and follow any redirects.
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string());
$data = curl_exec($curl);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
_error_log("getUsageFromURL: ERROR " . $exc->getMessage());
_error_log("getUsageFromURL: ERROR " . curl_errno($curl));
_error_log("getUsageFromURL: ERROR " . curl_error($curl));
}
if ($data) {
_error_log("getUsageFromURL: response header " . $data);
$content_length = "unknown";
$status = "unknown";
if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) {
$status = (int) $matches[1];
}
if (preg_match("/Content-Length: (\d+)/", $data, $matches)) {
$content_length = (int) $matches[1];
}
// http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if ($status == 200 || ($status > 300 && $status <= 308)) {
$result = $content_length;
}
} else {
_error_log("getUsageFromURL: ERROR no response data " . curl_error($curl));
}
curl_close($curl);
return (int) $result;
}
function getDirSize($dir) {
_error_log("getDirSize: start {$dir}");
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return foldersize($dir);
} else {
$command = "du -sb {$dir}";
exec($command . " < /dev/null 2>&1", $output, $return_val);
if ($return_val !== 0) {
_error_log("getDirSize: ERROR ON Command {$command}");
return 0;
} else {
if (!empty($output[0])) {
preg_match("/^([0-9]+).*/", $output[0], $matches);
}
if (!empty($matches[1])) {
_error_log("getDirSize: found {$matches[1]} from - {$output[0]}");
return intval($matches[1]);
}
_error_log("getDirSize: ERROR on pregmatch {$output[0]}");
return 0;
}
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/') . '/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function getDiskUsage() {
global $global;
$dir = getVideosDir() . "";
$obj = new stdClass();
$obj->disk_free_space = disk_free_space($dir);
$obj->disk_total_space = disk_total_space($dir);
$obj->videos_dir = getDirSize($dir);
$obj->disk_used = $obj->disk_total_space - $obj->disk_free_space;
$obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir;
$obj->disk_free_space_human = humanFileSize($obj->disk_free_space);
$obj->disk_total_space_human = humanFileSize($obj->disk_total_space);
$obj->videos_dir_human = humanFileSize($obj->videos_dir);
$obj->disk_used_human = humanFileSize($obj->disk_used);
$obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other);
// percentage of disk used
$obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100);
$obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100);
$obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100);
return $obj;
}
function unsetSearch() {
unset($_GET['searchPhrase']);
unset($_POST['searchPhrase']);
unset($_GET['search']);
unset($_GET['q']);
}
function encrypt_decrypt($string, $action) {
global $global;
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = $global['systemRootPath'];
while (strlen($secret_iv) < 16) {
$secret_iv .= $global['systemRootPath'];
}
// hash
$key = hash('sha256', $global['salt']);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} elseif ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
function compressString($string) {
if (function_exists("gzdeflate")) {
$string = gzdeflate($string, 9);
}
return $string;
}
function decompressString($string) {
if (function_exists("gzinflate")) {
$string = gzinflate($string);
}
return $string;
}
function encryptString($string) {
if (is_object($string)) {
$string = json_encode($string);
}
return encrypt_decrypt($string, 'encrypt');
}
function decryptString($string) {
return encrypt_decrypt($string, 'decrypt');
}
function getToken($timeout = 0, $salt = "") {
global $global;
$obj = new stdClass();
$obj->salt = $global['salt'] . $salt;
if (!empty($timeout)) {
$obj->time = time();
$obj->timeout = $obj->time + $timeout;
} else {
$obj->time = strtotime("Today 00:00:00");
$obj->timeout = strtotime("Today 23:59:59");
$obj->timeout += cacheExpirationTime();
}
$strObj = json_encode($obj);
//_error_log("Token created: {$strObj}");
return encryptString($strObj);
}
function isTokenValid($token, $salt = "") {
return verifyToken($token, $salt);
}
function verifyToken($token, $salt = "") {
global $global;
$obj = _json_decode(decryptString($token));
if (empty($obj)) {
_error_log("verifyToken invalid token");
return false;
}
if ($obj->salt !== $global['salt'] . $salt) {
_error_log("verifyToken salt fail");
return false;
}
$time = time();
if (!($time >= $obj->time && $time <= $obj->timeout)) {
_error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout");
return false;
}
return true;
}
class YPTvideoObject {
public $id;
public $title;
public $description;
public $thumbnails;
public $channelTitle;
public $videoLink;
public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) {
$this->id = $id;
$this->title = $title;
$this->description = $description;
$this->thumbnails = $thumbnails;
$this->channelTitle = $channelTitle;
$this->videoLink = $videoLink;
}
}
function isToShowDuration($type) {
$notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks');
if (in_array($type, $notShowTo)) {
return false;
} else {
return true;
}
}
function _dieAndLogObject($obj, $prefix = "") {
$objString = json_encode($obj);
_error_log($prefix . $objString);
die($objString);
}
function isAVideoPlayer() {
if (isVideo() || isSerie()) {
return true;
}
return false;
}
function isFirstPage() {
global $isFirstPage;
return !empty($isFirstPage);
}
function isVideo() {
global $isModeYouTube, $global;
if (!empty($global['doNotLoadPlayer'])) {
return false;
}
return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive();
}
function isVideoTypeEmbed() {
global $isVideoTypeEmbed;
if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) {
return $videos_id;
}
return false;
}
function isAudio() {
global $isAudio;
return !empty($isAudio);
}
function isSerie() {
return isPlayList();
}
function isPlayList() {
global $isPlayList, $isSerie;
return !empty($isSerie) || !empty($isPlayList);
}
function isChannel() {
global $isChannel;
if (!empty($isChannel) && !isVideo()) {
$user_id = 0;
if (empty($_GET['channelName'])) {
if (User::isLogged()) {
$user_id = User::getId();
} else {
return false;
}
} else {
$_GET['channelName'] = xss_esc($_GET['channelName']);
$user = User::getChannelOwner($_GET['channelName']);
if (!empty($user)) {
$user_id = $user['id'];
} else {
$user_id = $_GET['channelName'];
}
}
return $user_id;
}
return false;
}
function isEmbed() {
global $isEmbed, $global;
if (!empty($global['doNotLoadPlayer'])) {
return false;
}
return !empty($isEmbed);
}
function isLive() {
global $isLive, $global;
if (!empty($global['doNotLoadPlayer'])) {
return false;
}
if (!empty($isLive)) {
$live = getLiveKey();
if (empty($live)) {
$live = array('key' => false, 'live_servers_id' => false, 'live_index' => false);
}
$live['liveLink'] = isLiveLink();
return $live;
} else {
return false;
}
}
function isLiveLink() {
global $isLiveLink;
if (!empty($isLiveLink)) {
return $isLiveLink;
} else {
return false;
}
}
function getLiveKey() {
global $getLiveKey;
if (empty($getLiveKey)) {
return false;
}
return $getLiveKey;
}
function setLiveKey($key, $live_servers_id, $live_index = '') {
global $getLiveKey;
$parameters = Live::getLiveParametersFromKey($key);
$key = $parameters['key'];
$cleanKey = $parameters['cleanKey'];
if (empty($live_index)) {
$live_index = $parameters['live_index'];
}
$key = Live::getLiveKeyFromRequest($key, $live_index, $parameters['playlists_id_live']);
$getLiveKey = array('key' => $key, 'live_servers_id' => intval($live_servers_id), 'live_index' => $live_index, 'cleanKey' => $cleanKey);
return $getLiveKey;
}
function isVideoPlayerHasProgressBar() {
if (isLive()) {
$obj = AVideoPlugin::getObjectData('Live');
if (empty($obj->disableDVR)) {
return true;
}
} elseif (isAVideoPlayer()) {
return true;
}
return false;
}
function isHLS() {
global $video, $global;
if (isLive()) {
return true;
} elseif (!empty($video) && $video['type'] == 'video' && file_exists(getVideosDir() . "{$video['filename']}/index.m3u8")) {
return true;
}
return false;
}
function getRedirectUri() {
if (!empty($_GET['redirectUri'])) {
return $_GET['redirectUri'];
}
if (!empty($_SERVER["HTTP_REFERER"])) {
return $_SERVER["HTTP_REFERER"];
}
return getRequestURI();
}
function getRedirectToVideo($videos_id) {
$redirectUri = getRedirectUri();
$isEmbed = 0;
if (stripos($redirectUri, "embed") !== false) {
$isEmbed = 1;
}
$video = Video::getVideoLight($videos_id);
if(empty($video)){
return false;
}
return Video::getLink($videos_id, $video['clean_title'], $isEmbed);
}
function getRequestURI() {
if (empty($_SERVER['REQUEST_URI'])) {
return "";
}
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}
function getSelfURI() {
if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) {
return "";
}
$queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']);
$phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']);
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError";
$url = rtrim($url, '?');
return $url;
}
function isSameVideoAsSelfURI($url) {
return URLsAreSameVideo($url, getSelfURI());
}
function URLsAreSameVideo($url1, $url2) {
$videos_id1 = getVideoIDFromURL($url1);
$videos_id2 = getVideoIDFromURL($url2);
if (empty($videos_id1) || empty($videos_id2)) {
return false;
}
return $videos_id1 === $videos_id2;
}
function getVideos_id() {
global $_getVideos_id;
$videos_id = false;
if (isset($_getVideos_id)) {
return $_getVideos_id;
}
if (isVideo()) {
$videos_id = getVideoIDFromURL(getSelfURI());
if (empty($videos_id) && !empty($_REQUEST['videoName'])) {
$video = Video::getVideoFromCleanTitle($_REQUEST['videoName']);
if (!empty($video)) {
$videos_id = $video['id'];
}
}
setVideos_id($videos_id);
}
if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) {
$video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']);
if (!empty($video)) {
$videos_id = $video['id'];
}
}
$videos_id = videosHashToID($videos_id);
return $videos_id;
}
function setVideos_id($videos_id) {
global $_getVideos_id;
$_getVideos_id = $videos_id;
}
function getPlaylists_id() {
global $_isPlayList;
if (!isset($_isPlayList)) {
$_isPlayList = false;
if (isPlayList()) {
$_isPlayList = intval(@$_GET['playlists_id']);
if (empty($_isPlayList)) {
$videos_id = getVideos_id();
if (empty($videos_id)) {
$_isPlayList = false;
} else {
$v = Video::getVideoLight($videos_id);
if (empty($v) || empty($v['serie_playlists_id'])) {
$_isPlayList = false;
} else {
$_isPlayList = $v['serie_playlists_id'];
}
}
}
}
}
return $_isPlayList;
}
function isVideoOrAudioNotEmbed() {
if (!isVideo()) {
return false;
}
$videos_id = getVideos_id();
if (empty($videos_id)) {
return false;
}
$v = Video::getVideoLight($videos_id);
if (empty($v)) {
return false;
}
$types = array('audio', 'video');
if (in_array($v['type'], $types)) {
return true;
}
return false;
}
function getVideoIDFromURL($url) {
if (preg_match("/v=([0-9]+)/", $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) {
return intval($matches[1]);
}
if (AVideoPlugin::isEnabledByName('PlayLists')) {
if (preg_match('/player.php\?playlists_id=([0-9]+)/', $url, $matches)) {
$serie_playlists_id = intval($matches[1]);
$video = PlayLists::isPlayListASerie($serie_playlists_id);
if ($video) {
return $video['id'];
}
}
}
return false;
}
function getBackURL() {
global $global;
$backURL = getRedirectUri();
if (empty($backURL)) {
$backURL = getRequestURI();
}
if (isSameVideoAsSelfURI($backURL)) {
$backURL = getHomeURL();
}
return $backURL;
}
function getHomeURL() {
global $global, $advancedCustomUser, $advancedCustom;
if (isValidURL($advancedCustomUser->afterLoginGoToURL)) {
return $advancedCustomUser->afterLoginGoToURL;
} elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) {
return $advancedCustom->logoMenuBarURL;
}
return $global['webSiteRootURL'];
}
function isValidURL($url) {
//var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL));
if (empty($url) || !is_string($url)) {
return false;
}
if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) {
return true;
}
return false;
}
function hasLastSlash($word) {
return substr($word, -1) === '/';
}
function addLastSlash($word) {
return $word . (hasLastSlash($word) ? "" : "/");
}
function URLHasLastSlash() {
return hasLastSlash($_SERVER["REQUEST_URI"]);
}
function ucname($str) {
$str = ucwords(strtolower($str));
foreach (array('\'', '-') as $delim) {
if (strpos($str, $delim) !== false) {
$str = implode($delim, array_map('ucfirst', explode($delim, $str)));
}
}
return $str;
}
function sanitize_input($input) {
return htmlentities(strip_tags($input));
}
function sanitize_array_item(&$item, $key) {
$item = sanitize_input($item);
}
function getSEOComplement($parameters = array()) {
global $config;
$allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null;
$addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true;
$addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true;
$parts = array();
if (!empty($_GET['error'])) {
array_push($parts, __("Error"));
}
if ($addCategory && !empty($_GET['catName'])) {
array_push($parts, $_GET['catName']);
}
if (!empty($_GET['channelName'])) {
array_push($parts, $_GET['channelName']);
}
if (!empty($_GET['type'])) {
$type = $_GET['type'];
if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) {
array_push($parts, __(ucname($type)));
}
}
if (!empty($_GET['showOnly'])) {
array_push($parts, $_GET['showOnly']);
}
if (!empty($_GET['page'])) {
$page = intval($_GET['page']);
if ($page > 1) {
array_push($parts, sprintf(__("Page %d"), $page));
}
}
// Cleaning all entries in the $parts array
array_walk($parts, 'sanitize_array_item');
$txt = implode($config->getPageTitleSeparator(), $parts);
$txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt;
return $txt;
}
function getCurrentPage() {
if (!empty($_REQUEST['current'])) {
return intval($_REQUEST['current']);
} elseif (!empty($_POST['current'])) {
return intval($_POST['current']);
} elseif (!empty($_GET['current'])) {
return intval($_GET['current']);
} elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid
$start = intval($_GET['start']);
$length = intval($_GET['length']);
if (!empty($start) && !empty($length)) {
return floor($start / $length) + 1;
}
}
return 1;
}
function getRowCount($default = 1000) {
global $global;
if (!empty($_REQUEST['rowCount'])) {
$defaultN = intval($_REQUEST['rowCount']);
} elseif (!empty($_POST['rowCount'])) {
$defaultN = intval($_POST['rowCount']);
} elseif (!empty($_GET['rowCount'])) {
$defaultN = intval($_GET['rowCount']);
} elseif (!empty($_REQUEST['length'])) {
$defaultN = intval($_REQUEST['length']);
} elseif (!empty($_POST['length'])) {
$defaultN = intval($_POST['length']);
} elseif (!empty($_GET['length'])) {
$defaultN = intval($_GET['length']);
} elseif (!empty($global['rowCount'])) {
$defaultN = intval($global['rowCount']);
}
return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default;
}
function getSearchVar() {
if (!empty($_REQUEST['search'])) {
return $_REQUEST['search'];
} elseif (!empty($_REQUEST['q'])) {
return $_REQUEST['q'];
}
if (!empty($_REQUEST['searchPhrase'])) {
return $_REQUEST['searchPhrase'];
} elseif (!empty($_REQUEST['search']['value'])) {
return $_REQUEST['search']['value'];
}
return "";
}
$cleanSearchHistory = "";
function cleanSearchVar() {
global $cleanSearchHistory;
$search = getSearchVar();
if (!empty($search)) {
$cleanSearchHistory = $search;
}
$searchIdex = array('q', 'searchPhrase', 'search');
foreach ($searchIdex as $value) {
unset($_REQUEST[$value]);
unset($_POST[$value]);
unset($_GET[$value]);
}
}
function reloadSearchVar() {
global $cleanSearchHistory;
$_REQUEST['search'] = $cleanSearchHistory;
if (empty($_GET['search'])) {
$_GET['search'] = $cleanSearchHistory;
}
if (empty($_POST['search'])) {
$_POST['search'] = $cleanSearchHistory;
}
}
function wget($url, $filename, $debug = false) {
if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) {
return false;
}
if (wgetIsLocked($url)) {
if ($debug) {
_error_log("wget: ERROR the url is already downloading $url, $filename");
}
return false;
}
wgetLock($url);
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$content = @file_get_contents($url);
if (!empty($content) && file_put_contents($filename, $content) > 100) {
wgetRemoveLock($url);
return true;
}
wgetRemoveLock($url);
return false;
}
$cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate";
if ($debug) {
_error_log("wget Start ({$cmd}) ");
}
//echo $cmd;
exec($cmd);
wgetRemoveLock($url);
if (!file_exists($filename)) {
_error_log("wget: ERROR the url does not download $url, $filename");
return false;
}
if ($_SERVER['SCRIPT_NAME'] !== '/plugin/Live/m3u8.php' && empty(filesize($filename))) {
_error_log("wget: ERROR the url download but is empty $url, $filename");
return true;
}
return false;
}
/**
* Copy remote file over HTTP one small chunk at a time.
*
* @param $infile The full URL to the remote file
* @param $outfile The path where to save the file
*/
function copyfile_chunked($infile, $outfile) {
$chunksize = 10 * (1024 * 1024); // 10 Megs
/**
* parse_url breaks a part a URL into it's parts, i.e. host, path,
* query string, etc.
*/
$parts = parse_url($infile);
$i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
$o_handle = fopen($outfile, 'wb');
if ($i_handle == false || $o_handle == false) {
return false;
}
if (!empty($parts['query'])) {
$parts['path'] .= '?' . $parts['query'];
}
/**
* Send the request to the server for the file
*/
$request = "GET {$parts['path']} HTTP/1.1\r\n";
$request .= "Host: {$parts['host']}\r\n";
$request .= "User-Agent: Mozilla/5.0\r\n";
$request .= "Keep-Alive: 115\r\n";
$request .= "Connection: keep-alive\r\n\r\n";
fwrite($i_handle, $request);
/**
* Now read the headers from the remote server. We'll need
* to get the content length.
*/
$headers = array();
while (!feof($i_handle)) {
$line = fgets($i_handle);
if ($line == "\r\n")
break;
$headers[] = $line;
}
/**
* Look for the Content-Length header, and get the size
* of the remote file.
*/
$length = 0;
foreach ($headers as $header) {
if (stripos($header, 'Content-Length:') === 0) {
$length = (int) str_replace('Content-Length: ', '', $header);
break;
}
}
/**
* Start reading in the remote file, and writing it to the
* local file one chunk at a time.
*/
$cnt = 0;
while (!feof($i_handle)) {
$buf = '';
$buf = fread($i_handle, $chunksize);
$bytes = fwrite($o_handle, $buf);
if ($bytes == false) {
return false;
}
$cnt += $bytes;
/**
* We're done reading when we've reached the conent length
*/
if ($cnt >= $length)
break;
}
fclose($i_handle);
fclose($o_handle);
return $cnt;
}
function wgetLockFile($url) {
return getTmpDir("YPTWget") . md5($url) . ".lock";
}
function wgetLock($url) {
$file = wgetLockFile($url);
return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX);
}
function wgetRemoveLock($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function getLockFile($name) {
return getTmpDir("YPTLockFile") . md5($name) . ".lock";
}
function setLock($name) {
$file = getLockFile($name);
return file_put_contents($file, time());
}
function isLock($name, $timeout = 60) {
$file = getLockFile($name);
if (file_exists($file)) {
$time = intval(file_get_contents($file));
if ($time + $timeout < time()) {
return false;
}
}
}
function removeLock($name) {
$filename = getLockFile($name);
if (!file_exists($filename)) {
return false;
}
return unlink($filename);
}
function wgetIsLocked($url) {
$filename = wgetLockFile($url);
if (!file_exists($filename)) {
return false;
}
$time = intval(file_get_contents($filename));
if (time() - $time > 36000) { // more then 10 hours
unlink($filename);
return false;
}
return true;
}
// due the some OS gives a fake is_writable response
function isWritable($dir) {
$dir = rtrim($dir, '/') . '/';
$file = $dir . uniqid();
$result = false;
$time = time();
if (@file_put_contents($file, $time)) {
if ($fileTime = @file_get_contents($file)) {
if ($fileTime == $time) {
$result = true;
}
}
}
@unlink($file);
return $result;
}
function _isWritable($dir) {
if (!isWritable($dir)) {
return false;
}
$tmpFile = "{$dir}" . uniqid();
$bytes = @file_put_contents($tmpFile, time());
@unlink($tmpFile);
return !empty($bytes);
}
function getTmpDir($subdir = "") {
global $global;
if (empty($_SESSION['getTmpDir'])) {
$_SESSION['getTmpDir'] = array();
}
if (empty($_SESSION['getTmpDir'][$subdir . "_"])) {
$tmpDir = sys_get_temp_dir();
if (empty($tmpDir) || !_isWritable($tmpDir)) {
$tmpDir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR;
}
$tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$tmpDir = "{$tmpDir}{$subdir}";
$tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
_session_start();
$_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir;
} else {
$tmpDir = $_SESSION['getTmpDir'][$subdir . "_"];
}
return $tmpDir;
}
function getTmpFile() {
return getTmpDir("tmpFiles") . uniqid();
}
function getMySQLDate() {
global $global;
$sql = "SELECT now() as time FROM configurations LIMIT 1";
// I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data['time'];
} else {
$row = false;
}
return $row;
}
function _file_put_contents($filename, $data, $flags = 0, $context = null) {
make_path($filename);
return file_put_contents($filename, $data, $flags, $context);
}
function html2plainText($html) {
$text = strip_tags($html);
$text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text));
return $text;
}
function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') {
if (empty($paceholder)) {
$paceholder = __("Password");
}
?>
>
>
" . PHP_EOL;
} else {
return __LINE__;
}
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
echo "Error 1 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL;
} else {
return __LINE__;
}
return false;
}
function _json_encode($object) {
if (empty($object)) {
return false;
}
if (is_string($object)) {
return $object;
}
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 1 Found: " . json_last_error_msg());
$object = object_to_array($object);
$json = json_encode($object);
if (json_last_error()) {
_error_log("_json_encode: Error 2 Found: " . json_last_error_msg());
$json = json_encode($object, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 3 Found: " . json_last_error_msg());
$objectEncoded = $object;
array_walk_recursive($objectEncoded, function (&$item) {
if (is_string($item)) {
$item = utf8_encode($item);
}
});
$json = json_encode($objectEncoded);
if (json_last_error()) {
_error_log("_json_encode: Error 4 Found: " . json_last_error_msg());
$json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 5 Found: " . json_last_error_msg());
$objectDecoded = $object;
array_walk_recursive($objectDecoded, function (&$item) {
if (is_string($item)) {
$item = utf8_decode($item);
}
});
$json = json_encode($objectDecoded);
if (json_last_error()) {
_error_log("_json_encode: Error 6 Found: " . json_last_error_msg());
$json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE);
if (json_last_error()) {
_error_log("_json_encode: Error 7 Found: " . json_last_error_msg());
}
}
}
}
}
}
}
return $json;
}
function _json_decode($object) {
if (empty($object)) {
return false;
}
if (!is_string($object)) {
return $object;
}
return json_decode($object);
}
// this will make sure the strring will fits in the database field
function _substr($string, $start, $length = null) {
// make sure the name is not chunked in case of multibyte string
if (function_exists("mb_strcut")) {
return mb_strcut($string, $start, $length, "UTF-8");
} else {
return substr($string, $start, $length);
}
}
function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") {
global $global, $advancedCustom;
if ($total < 2) {
return '';
}
if (empty($page)) {
$page = getCurrentPage();
}
$isInfiniteScroll = !empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector);
$uid = md5($link);
if ($total < $maxVisible) {
$maxVisible = $total;
}
if (empty($link)) {
$link = getSelfURI();
if (preg_match("/(current=[0-9]+)/i", $link, $match)) {
$link = str_replace($match[1], "current={page}", $link);
} else {
$link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}';
}
}
$class = "";
if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) {
$class = "infiniteScrollPagination{$uid} hidden";
}
if ($isInfiniteScroll && $page > 1) {
$pageForwardLink = str_replace("{page}", $page + 1, $link);
return "";
}
$pag = ' ';
if ($isInfiniteScroll) {
$content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php');
$pag .= str_replace(
array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'),
array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector),
$content
);
}
return $pag;
}
function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") {
global $global, $advancedCustom;
include $global['systemRootPath'] . 'objects/functiongetShareMenu.php';
}
function getSharePopupButton($videos_id, $url = "", $title = "") {
global $global, $advancedCustom;
if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) {
return false;
}
$video['id'] = $videos_id;
include $global['systemRootPath'] . 'view/include/socialModal.php';
}
function forbiddenPage($message, $logMessage = false) {
global $global;
$_REQUEST['403ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/forbiddenPage.php';
exit;
}
define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |
E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
if (!isCommandLineInterface() && !isAVideoEncoder()) {
register_shutdown_function('avidoeShutdown');
}
function avidoeShutdown() {
global $global;
$error = error_get_last();
if ($error && ($error['type'] & E_FATAL)) {
_error_log($error, AVideoLog::$ERROR);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo '' . PHP_EOL;
include $global['systemRootPath'] . 'view/maintanance.html';
exit;
}
}
function videoNotFound($message, $logMessage = false) {
global $global;
$_REQUEST['404ErrorMsg'] = $message;
if ($logMessage) {
_error_log($message);
}
include $global['systemRootPath'] . 'view/videoNotFound.php';
exit;
}
function isForbidden() {
global $global;
if (!empty($global['isForbidden'])) {
return true;
}
return false;
}
function diskUsageBars() {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function getDomain() {
global $global, $_getDomain;
if (isset($_getDomain)) {
return $_getDomain;
}
if (empty($_SERVER['HTTP_HOST'])) {
$parse = parse_url($global['webSiteRootURL']);
$domain = $parse['host'];
} else {
$domain = $_SERVER['HTTP_HOST'];
}
$domain = str_replace("www.", "", $domain);
$domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain;
$_getDomain = $domain;
return $domain;
}
/**
* It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc.
*
* From the IETF RFC4122:
* 8-4-4-4-12
* @return string
*/
function getDeviceID($useRandomString = true) {
$ip = md5(getRealIpAddr());
if (empty($_SERVER['HTTP_USER_AGENT'])) {
$device = "unknowDevice-{$ip}";
$device .= '-' . intval(User::getId());
return $device;
}
if (empty($useRandomString)) {
$device = 'ypt-' . get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']);
$device = str_replace(
array('[', ']', ' '),
array('', '', '_'), $device);
$device .= '-' . intval(User::getId());
return $device;
}
$cookieName = "yptDeviceID";
if (empty($_COOKIE[$cookieName])) {
if (empty($_GET[$cookieName])) {
$id = uniqidV4();
$_GET[$cookieName] = $id;
}
if (empty($_SESSION[$cookieName])) {
_session_start();
$_SESSION[$cookieName] = $_GET[$cookieName];
} else {
$_GET[$cookieName] = $_SESSION[$cookieName];
}
if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) {
return "getDeviceIDError";
}
$_COOKIE[$cookieName] = $_GET[$cookieName];
return $_GET[$cookieName];
}
return $_COOKIE[$cookieName];
}
function deviceIdToObject($deviceID) {
$parts = explode('-', $deviceID);
$obj = new stdClass();
$obj->browser = '';
$obj->os = '';
$obj->ip = '';
$obj->user_agent = '';
$obj->users_id = 0;
foreach ($parts as $key => $value) {
$parts[$key] = str_replace('_', ' ', $value);
}
switch ($parts[0]) {
case 'ypt':
$obj->browser = $parts[1];
$obj->os = $parts[2];
$obj->ip = $parts[3];
$obj->user_agent = $parts[4];
$obj->users_id = $parts[5];
break;
case 'unknowDevice':
$obj->browser = $parts[0];
$obj->os = 'unknow OS';
$obj->ip = $parts[1];
$obj->user_agent = 'unknow UA';
$obj->users_id = $parts[2];
break;
default:
break;
}
return $obj;
}
function uniqidV4() {
$randomString = openssl_random_pseudo_bytes(16);
$time_low = bin2hex(substr($randomString, 0, 4));
$time_mid = bin2hex(substr($randomString, 4, 2));
$time_hi_and_version = bin2hex(substr($randomString, 6, 2));
$clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2));
$node = bin2hex(substr($randomString, 10, 6));
/**
* Set the four most significant bits (bits 12 through 15) of the
* time_hi_and_version field to the 4-bit version number from
* Section 4.1.3.
* @see http://tools.ietf.org/html/rfc4122#section-4.1.3
*/
$time_hi_and_version = hexdec($time_hi_and_version);
$time_hi_and_version = $time_hi_and_version >> 4;
$time_hi_and_version = $time_hi_and_version | 0x4000;
/**
* Set the two most significant bits (bits 6 and 7) of the
* clock_seq_hi_and_reserved to zero and one, respectively.
*/
$clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;
return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
}
// guid
function _setcookie($cookieName, $value, $expires = 0) {
if (empty($expires)) {
if (empty($config) || !is_object($config)) {
$config = new Configuration();
}
$expires = time() + $config->getSession_timeout();
}
if (version_compare(phpversion(), '7.3', '>=')) {
$cookie_options = array(
'expires' => $expires,
'path' => '/',
'domain' => getDomain(),
'secure' => true,
'httponly' => false,
'samesite' => 'None');
return setcookie($cookieName, $value, $cookie_options);
} else {
return setcookie($cookieName, $value, (int) $expires, "/", getDomain());
}
}
function _unsetcookie($cookieName) {
$domain = getDomain();
$expires = strtotime("-10 years");
$value = "";
_setcookie($cookieName, $value, $expires);
setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires);
setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain));
setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", "." . $domain);
setcookie($cookieName, $value, (int) $expires, "/", $domain);
setcookie($cookieName, $value, (int) $expires, "/");
setcookie($cookieName, $value, (int) $expires);
unset($_COOKIE[$cookieName]);
}
/**
* This function is not 100% but try to tell if the site is in an iFrame
* @global type $global
* @return boolean
*/
function isIframeInDifferentDomain() {
global $global;
if (!isIframe()) {
return false;
}
return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']);
}
function isIframe() {
global $global;
if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') {
return true;
}
if (empty($_SERVER['HTTP_REFERER'])) {
return false;
}
return true;
}
function getCredentialsURL() {
global $global;
return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1";
}
function gotToLoginAndComeBackHere($msg) {
global $global;
if (User::isLogged()) {
forbiddenPage($msg);
exit;
}
if (!empty($_GET['comebackhere'])) {
return false;
}
header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1");
exit;
}
function setAlertMessage($msg, $type = "msg") {
_session_start();
$_SESSION['YPTalertMessage'][] = array($msg, $type);
}
function setToastMessage($msg) {
setAlertMessage($msg, "toast");
}
function showAlertMessage() {
if (!empty($_SESSION['YPTalertMessage'])) {
foreach ($_SESSION['YPTalertMessage'] as $value) {
if (!empty($value[0])) {
if (empty($_GET[$value[1]])) {
$_GET[$value[1]] = array();
}
$_GET[$value[1]][] = $value[0];
}
}
_session_start();
unset($_SESSION['YPTalertMessage']);
}
$joinString = array('error', 'msg', 'success');
foreach ($joinString as $value) {
if (!empty($_GET[$value]) && is_array($_GET[$value])) {
$_GET[$value] = array_unique($_GET[$value]);
$newStr = array();
foreach ($_GET[$value] as $value2) {
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = implode("
", $newStr);
}
}
$check = array('error', 'msg', 'success', 'toast');
foreach ($check as $value) {
if (!empty($_GET[$value])) {
if (is_array($_GET[$value])) {
$newStr = array();
foreach ($_GET[$value] as $key => $value2) {
$value2 = str_replace('"', "''", $value2);
if (!empty($value2)) {
$newStr[] = $value2;
}
}
$_GET[$value] = $newStr;
} else {
$_GET[$value] = str_replace('"', "''", $_GET[$value]);
}
}
}
echo "/** showAlertMessage **/", PHP_EOL;
if (!empty($_GET['error'])) {
echo 'avideoAlertError("' . $_GET['error'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['msg'])) {
echo 'avideoAlertInfo("' . $_GET['msg'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['success'])) {
echo 'avideoAlertSuccess("' . $_GET['success'] . '");';
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
if (!empty($_GET['toast'])) {
if (!is_array($_GET['toast'])) {
$_GET['toast'] = array($_GET['toast']);
} else {
$_GET['toast'] = array_unique($_GET['toast']);
}
foreach ($_GET['toast'] as $key => $value) {
$hideAfter = strlen(strip_tags($value)) * 150;
if ($hideAfter < 3000) {
$hideAfter = 3000;
}
if ($hideAfter > 15000) {
$hideAfter = 15000;
}
echo '$.toast({
text: "' . $value . '",
hideAfter: ' . $hideAfter . ' // in milli seconds
});console.log("Toast Hide after ' . $hideAfter . '");';
}
echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");';
}
echo PHP_EOL, "/** showAlertMessage END **/";
}
function getResolutionLabel($res) {
if ($res == 720) {
return "" . getResolutionText($res) . "";
} elseif ($res == 1080) {
return "" . getResolutionText($res) . "";
} elseif ($res == 1440) {
return "" . getResolutionText($res) . "";
} elseif ($res == 2160) {
return "" . getResolutionText($res) . "";
} elseif ($res == 4320) {
return "" . getResolutionText($res) . "";
} else {
return '';
}
}
function getResolutionText($res) {
if ($res == 720) {
return "HD";
} elseif ($res == 1080) {
return "FHD";
} elseif ($res == 1440) {
return "FHD+";
} elseif ($res == 2160) {
return "4K";
} elseif ($res == 4320) {
return "8K";
} else {
return '';
}
}
// just realize the readdir is a lot faster then glob
function _glob($dir, $pattern) {
global $_glob;
if (empty($dir)) {
return array();
}
if (empty($_glob)) {
$_glob = array();
}
$name = md5($dir . $pattern);
if (isset($_glob[$name])) {
return $_glob[$name];
}
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$array = array();
if ($handle = opendir($dir)) {
$count = 0;
while (false !== ($file_name = readdir($handle))) {
if ($file_name == '.' || $file_name == '..') {
continue;
}
//_error_log("_glob: {$dir}{$file_name} [$pattern]");
//var_dump($pattern, $file_name, preg_match($pattern, $file_name));
if (preg_match($pattern, $file_name)) {
$array[] = "{$dir}{$file_name}";
}
}
closedir($handle);
}
$_glob[$name] = $array;
return $array;
}
function globVideosDir($filename, $filesOnly = false) {
global $global;
if (empty($filename)) {
return array();
}
$cleanfilename = Video::getCleanFilenameFromFile($filename);
$dir = getVideosDir();
if (is_dir($dir . $filename)) {
$dir = $dir . $filename;
$cleanfilename = '';
}
$pattern = "/{$cleanfilename}.*";
if (!empty($filesOnly)) {
$formats = getValidFormats();
$pattern .= ".(" . implode("|", $formats) . ")";
}
$pattern .= "/";
return _glob($dir, $pattern);
}
function getValidFormats() {
$video = array('webm', 'mp4', 'm3u8');
$audio = array('mp3', 'ogg');
$image = array('jpg', 'gif', 'webp');
return array_merge($video, $audio, $image);
}
function isValidFormats($format) {
$format = str_replace(".", "", $format);
return in_array($format, getValidFormats());
}
function getTimerFromDates($startTime, $endTime = 0) {
if (!is_int($startTime)) {
$startTime = strtotime($startTime);
}
if (!is_int($endTime)) {
$endTime = strtotime($endTime);
}
if (empty($endTime)) {
$endTime = time();
}
$timer = abs($endTime - $startTime);
$uid = uniqid();
return "";
}
function getServerClock() {
$id = uniqid();
$today = getdate();
$html = '00:00:00';
$html .= "";
return $html;
}
/**
* Xsendfile and FFMPEG are required for this feature
* @global type $global
* @param type $filepath
* @return boolean
*/
function downloadHLS($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("downloadHLS: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("downloadHLS was not possible");
}
$outputpath = $output['path'];
$outputfilename = $output['filename'];
if (!empty($_REQUEST['title'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\'));
} elseif (!empty($_REQUEST['file'])) {
$quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4";
} else {
$quoted = $outputfilename;
}
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("X-Sendfile: {$outputpath}");
exit;
}
function playHLSasMP4($filepath) {
global $global;
if (!CustomizeUser::canDownloadVideos()) {
_error_log("playHLSasMP4: CustomizeUser::canDownloadVideos said NO");
return false;
}
if (!file_exists($filepath)) {
_error_log("playHLSasMP4: file NOT found: {$filepath}");
return false;
}
$output = m3u8ToMP4($filepath);
if (empty($output)) {
die("playHLSasMP4 was not possible");
}
$outputpath = $output['path'];
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Content-type: video/mp4');
header('Content-Length: ' . filesize($outputpath));
header("X-Sendfile: {$outputpath}");
exit;
}
function m3u8ToMP4($input) {
$videosDir = getVideosDir();
$outputfilename = str_replace($videosDir, "", $input);
$parts = explode("/", $outputfilename);
$resolution = Video::getResolutionFromFilename($input);
$outputfilename = $parts[0] . "_{$resolution}_.mp4";
$outputpath = "{$videosDir}cache/downloads/{$outputfilename}";
make_path($outputpath);
if (empty($outputfilename)) {
_error_log("downloadHLS: empty outputfilename {$outputfilename}");
return false;
}
//var_dump(!preg_match('/^http/i', $input), filesize($input), preg_match('/.m3u8$/i', $input));
if (!preg_match('/^http/i', $input) && (filesize($input) <= 10 || preg_match('/.m3u8$/i', $input))) { // dummy file
$filepath = escapeshellcmd(pathToRemoteURL($input, true));
} else {
$filepath = escapeshellcmd($input);
}
$outputpath = escapeshellcmd($outputpath);
if (!file_exists($outputpath)) {
$command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
_error_log("downloadHLS: Exec Command ({$command})");
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 1 " . implode(PHP_EOL, $output));
$command = get_ffmpeg() . " -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}";
//var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit;
exec($command . " 2>&1", $output, $return);
if (!empty($return)) {
_error_log("downloadHLS: ERROR 2 " . implode(PHP_EOL, $output));
return false;
}
}
}
return array('path' => $outputpath, 'filename' => $outputfilename);
}
function getSocialModal($videos_id, $url = "", $title = "") {
global $global;
$video['id'] = $videos_id;
$sharingUid = uniqid();
ob_start();
?>
$contents, 'id' => $sharingUid);
}
function getCroppie(
$buttonTitle,
$callBackJSFunction,
$resultWidth,
$resultHeight,
$viewportWidth = 0,
$boundary = 25,
$viewportHeight = 0
) {
global $global;
if (empty($viewportWidth)) {
$viewportWidth = $resultWidth;
}
$zoom = 0;
if (empty($viewportHeight)) {
$zoom = ($viewportWidth / $resultWidth);
$viewportHeight = $zoom * $resultHeight;
}
$boundaryWidth = $viewportWidth + $boundary;
$boundaryHeight = $viewportHeight + $boundary;
$uid = uniqid();
ob_start();
include $global['systemRootPath'] . 'objects/functionCroppie.php';
$contents = ob_get_contents();
ob_end_clean();
$callBackJSFunction = addcslashes($callBackJSFunction, "'");
return array(
"html" => $contents,
"id" => "croppie{$uid}",
"uploadCropObject" => "uploadCrop{$uid}",
"getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});",
"createCroppie" => "createCroppie{$uid}",
"restartCroppie" => "restartCroppie{$uid}"
);
}
function saveCroppieImage($destination, $postIndex = "imgBase64") {
if (empty($_POST[$postIndex])) {
return false;
}
$fileData = base64DataToImage($_POST[$postIndex]);
return file_put_contents($destination, $fileData);
}
function get_ffmpeg($ignoreGPU = false) {
global $global;
//return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" ';
//return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" ';
$ffmpeg = 'ffmpeg ';
if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) {
$ffmpeg .= ' --enable-nvenc ';
}
if (!empty($global['ffmpeg'])) {
$ffmpeg = "{$global['ffmpeg']}{$ffmpeg}";
}
return $ffmpeg;
}
function isHTMLPage($url) {
if ($type = getHeaderContentTypeFromURL($url)) {
if (preg_match('/text\/html/i', $type)) {
return true;
}
}
return false;
}
function getHeaderContentTypeFromURL($url) {
if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) {
return $type;
}
return false;
}
function canFullScreen() {
global $doNotFullScreen;
if (!empty($doNotFullScreen) || isSerie() || !isVideo()) {
return false;
}
return true;
}
function getTinyMCE($id) {
global $global;
ob_start();
include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
function pathToRemoteURL($filename, $forceHTTP = false) {
global $pathToRemoteURL, $global;
if (!isset($pathToRemoteURL)) {
$pathToRemoteURL = array();
}
if (isset($pathToRemoteURL[$filename])) {
return $pathToRemoteURL[$filename];
}
if (!file_exists($filename) || filesize($filename) < 1000) {
$fileName = getFilenameFromPath($filename);
if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) {
$source = $yptStorage->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) {
$source = $aws_s3->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) {
$source = $bb_b2->getAddress("{$fileName}");
$url = $source['url'];
} else
if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) {
$source = $ftp->getAddress("{$fileName}");
$url = $source['url'];
}
}
if (empty($url)) {
if ($forceHTTP) {
$url = str_replace(getVideosDir(), getCDN() . "videos/", $filename);
} else {
$url = $filename;
}
}
//$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url);
$pathToRemoteURL[$filename] = $url;
return $url;
}
function getFilenameFromPath($path) {
global $global;
$fileName = str_replace(getVideosDir() . "", "", $path);
$fileName = Video::getCleanFilenameFromFile($fileName);
return $fileName;
}
function showCloseButton() {
global $global, $showCloseButtonIncluded;
if (!empty($showCloseButtonIncluded)) {
return '';
}
if (isSerie()) {
return '';
}
if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) {
if (!empty($obj->playVideoOnFullscreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) {
if (!empty($obj->playLiveInFullScreen)) {
$_REQUEST['showCloseButton'] = 1;
}
}
if (!empty($_REQUEST['showCloseButton'])) {
$showCloseButtonIncluded = 1;
include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php';
}
return '';
}
function getThemes() {
global $_getThemes, $global;
if (isset($_getThemes)) {
return $_getThemes;
}
$_getThemes = array();
foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) {
$fileEx = basename($filename, ".css");
$_getThemes[] = $fileEx;
}
return $_getThemes;
}
function getCurrentTheme() {
global $config;
if (!empty($_COOKIE['customCSS'])) {
return $_COOKIE['customCSS'];
}
return $config->getTheme();
}
/*
* $users_id="" or 0 means send messages to all users
* $users_id="-1" means send to no one
*/
function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") {
if (AVideoPlugin::isEnabledByName('YPTSocket')) {
if (!is_string($msg)) {
$msg = json_encode($msg);
}
$obj = YPTSocket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern);
if ($obj->error && !empty($obj->msg)) {
_error_log("sendSocketMessage " . $obj->msg);
}
return $obj;
}
return false;
}
function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") {
if (!is_array($users_id)) {
$users_id = array($users_id);
}
$resp = array();
foreach ($users_id as $value) {
$resp[] = sendSocketMessage($msg, $callbackJSFunction, $value);
}
return $resp;
}
function sendSocketMessageToAll($msg, $callbackJSFunction = "", $send_to_uri_pattern = "") {
return sendSocketMessage($msg, $callbackJSFunction, "", $send_to_uri_pattern);
}
function sendSocketMessageToNone($msg, $callbackJSFunction = "") {
return sendSocketMessage($msg, $callbackJSFunction, -1);
}
function execAsync($command) {
//$command = escapeshellarg($command);
// If windows, else
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
//echo $command;
//$pid = system("start /min ".$command. " > NUL");
//$commandString = "start /B " . $command;
//pclose($pid = popen($commandString, "r"));
_error_log($command);
$pid = exec($command, $output, $retval);
_error_log('execAsync: ' . json_encode($output) . ' ' . $retval);
} else {
$newCommand = $command . " > /dev/null 2>&1 & echo $!; ";
_error_log($newCommand);
$pid = exec($newCommand);
}
return $pid;
}
function killProcess($pid) {
$pid = intval($pid);
if (empty($pid)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
exec("taskkill /F /PID $pid");
} else {
exec("kill -9 $pid");
}
return true;
}
function getPIDUsingPort($port) {
$port = intval($port);
if (empty($port)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$command = 'netstat -ano | findstr ' . $port;
exec($command, $output, $retval);
$pid = 0;
foreach ($output as $value) {
if (preg_match('/LISTENING[^0-9]+([0-9]+)/i', $value, $matches)) {
if (!empty($matches[1])) {
$pid = intval($matches[1]);
return $pid;
}
}
}
} else {
$command = 'lsof -n -i :' . $port . ' | grep LISTEN';
exec($command, $output, $retval);
$pid = 0;
foreach ($output as $value) {
if (preg_match('/[^ ] +([0-9]+).*/i', $value, $matches)) {
if (!empty($matches[1])) {
$pid = intval($matches[1]);
return $pid;
}
}
}
}
return false;
}
function isURL200($url, $forceRecheck = false) {
global $_isURL200;
$name = "isURL200" . DIRECTORY_SEPARATOR . md5($url);
if (empty($forceRecheck)) {
$result = ObjectYPT::getCache($name, 30);
if (!empty($result)) {
$object = _json_decode($result);
return $object->result;
}
}
$object = new stdClass();
$object->url = $url;
$object->forceRecheck = $forceRecheck;
//error_log("isURL200 checking URL {$url}");
$headers = @get_headers($url);
if (!is_array($headers)) {
$headers = array($headers);
}
$object->result = false;
foreach ($headers as $value) {
if (
strpos($value, '200') ||
strpos($value, '302') ||
strpos($value, '304')
) {
$object->result = true;
break;
} else {
//_error_log('isURL200: '.$value);
}
}
ObjectYPT::setCache($name, json_encode($object));
return $object->result;
}
function isURL200Clear() {
$tmpDir = ObjectYPT::getCacheDir();
$cacheDir = $tmpDir . "isURL200" . DIRECTORY_SEPARATOR;
//_error_log("Live::isURL200Clear [{$cacheDir}]");
rrmdir($cacheDir);
exec('rm -R ' . $cacheDir);
}
function getStatsNotifications($force_recreate = false) {
$cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications";
if ($force_recreate) {
Live::deleteStatsCache();
} else {
$json = ObjectYPT::getCache($cacheName, 0, true);
}
if (empty($json)) {
_error_log('getStatsNotifications: 1 ' . json_encode(debug_backtrace()));
$json = Live::getStats();
$json = object_to_array($json);
if (empty($json['applications']) && is_array($json)) {
$json['applications'] = array();
foreach ($json as $key => $value) {
if (empty($value['applications'])) {
continue;
}
$json['applications'] = array_merge($json['applications'], $value['applications']);
unset($json[$key]);
}
}
$appArray = AVideoPlugin::getLiveApplicationArray();
if (!empty($appArray)) {
if (empty($json)) {
$json = array();
}
$json['error'] = false;
if (empty($json['msg'])) {
$json['msg'] = "OFFLINE";
}
$json['nclients'] = count($appArray);
if (empty($json['applications'])) {
$json['applications'] = array();
}
$json['applications'] = array_merge($json['applications'], $appArray);
}
$count = 0;
if (!isset($json['total'])) {
$json['total'] = 0;
}
if (!empty($json['applications'])) {
$json['total'] += count($json['applications']);
}
while (!empty($json[$count])) {
$json['total'] += count($json[$count]['applications']);
$count++;
}
if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) {
$json['countLiveStream'] = $json['total'];
}
if (!empty($json['applications'])) {
foreach ($json['applications'] as $key => $value) {
if (empty($value['users_id']) && !empty($value['user'])) {
$u = User::getFromUsername($value['user']);
$json['applications'][$key]['users_id'] = $u['id'];
}
}
}
$cache = ObjectYPT::setCache($cacheName, $json);
_error_log('Live::createStatsCache ' . json_encode($cache));
} else {
//_error_log('getStatsNotifications: 2 cached result');
$json = object_to_array($json);
}
return $json;
}
function getSocketConnectionLabel() {
$html = '
' . __('Disconnected') . '
' . __('Connected') . '
';
return $html;
}
function getSocketVideoClassName($videos_id) {
return 'total_on_videos_id_' . $videos_id;
}
function getSocketLiveClassName($key, $live_servers_id) {
return 'total_on_live_' . $key . '_' . intval($live_servers_id);
}
function getSocketLiveLinksClassName($live_links_id) {
return 'total_on_live_links_id_' . $live_links_id;
}
function getLiveUsersLabelVideo($videos_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") {
if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) {
return LiveUsers::getLabels(getSocketVideoClassName($videos_id), $totalViews, $viewsClass, $counterClass, 'video');
}
}
function getLiveUsersLabelLive($key, $live_servers_id, $viewsClass = "label label-default", $counterClass = "label label-primary") {
if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) {
$totalViews = 0;
if (User::isLogged()) {
$totalViews = LiveUsers::getTotalUsers($key, $live_servers_id);
}
return LiveUsers::getLabels(getSocketLiveClassName($key, $live_servers_id), $totalViews, $viewsClass, $counterClass, 'live');
}
}
function getLiveUsersLabelLiveLinks($liveLinks_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") {
if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getWatchingNowLabel")) {
return LiveUsers::getWatchingNowLabel(getSocketLiveLinksClassName($liveLinks_id), "label label-primary", '', $viewsClass, 'livelinks');
}
}
function getLiveUsersLabel($viewsClass = "label label-default", $counterClass = "label label-primary") {
if (AVideoPlugin::isEnabledByName('LiveUsers')) {
$live = isLive();
if (!empty($live)) {
if (!empty($live['key'])) {
return getLiveUsersLabelLive($live['key'], $live['live_servers_id'], $viewsClass, $counterClass);
} else if (!empty($live['liveLinks_id'])) {
return getLiveUsersLabelLiveLinks($live['liveLinks_id'], null, $viewsClass, $counterClass);
}
} else {
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$v = new Video("", "", $videos_id);
$totalViews = $v->getViews_count();
return getLiveUsersLabelVideo($videos_id, $totalViews, $viewsClass, $counterClass);
}
}
}
return "";
}
function getLiveUsersLabelHTML($viewsClass = "label label-default", $counterClass = "label label-primary") {
global $global;
ob_start();
include $global['systemRootPath'] . 'plugin/Live/view/onlineLabel.php';
$htmlMediaTag = '';
$htmlMediaTag .= ob_get_contents();
ob_end_clean();
$htmlMediaTag .= getLiveUsersLabel($viewsClass, $counterClass);
$htmlMediaTag .= '
';
return $htmlMediaTag;
}
function getHTMLTitle($titleArray) {
global $config, $global;
if (!is_array($titleArray)) {
$titleArray = array();
}
$titleArray[] = $config->getWebSiteTitle();
$title = implode($config->getPageTitleSeparator(), $titleArray);
$global['pageTitle'] = $title;
return "{$title}";
}
function getButtonSignInAndUp() {
$signIn = getButtonSignIn();
$signUp = getButtonSignUp();
$html = $signIn . $signUp;
if (!empty($signIn) && !empty($signIn)) {
return '' . $html . '
';
} else {
return $html;
}
}
function getButtonSignUp() {
global $global;
$obj = AVideoPlugin::getDataObject('CustomizeUser');
if (!empty($obj->disableNativeSignUp)) {
return '';
}
$url = $global['webSiteRootURL'] . 'signUp';
$url = addQueryStringParameter($url, 'redirectUri', getRedirectUri());
$html = ' ' . __("Sign Up") . ' ';
return $html;
}
function getButtonSignIn() {
global $global;
$obj = AVideoPlugin::getDataObject('CustomizeUser');
if (!empty($obj->disableNativeSignIn)) {
return '';
}
$url = $global['webSiteRootURL'] . 'user';
$url = addQueryStringParameter($url, 'redirectUri', getRedirectUri());
$html = ' ' . __("Sign In") . ' ';
return $html;
}
function getTitle() {
global $global;
if (empty($global['pageTitle'])) {
$url = getSelfURI();
$global['pageTitle'] = str_replace($global['webSiteRootURL'], '', $url);
if (preg_match('/\/plugin\/([^\/])/i', $url, $matches)) {
$global['pageTitle'] = __('Plugin') . ' ' . __($matches[1]);
}
$title = $global['pageTitle'];
}
return $global['pageTitle'];
}
function outputAndContinueInBackground() {
global $outputAndContinueInBackground;
if (!empty($outputAndContinueInBackground)) {
return false;
}
$outputAndContinueInBackground = 1;
@session_write_close();
//_mysql_close();
// Instruct PHP to continue execution
ignore_user_abort(true);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
ob_start();
@header("Connection: close");
@header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
}
function cleanUpRowFromDatabase($row) {
if (is_array($row)) {
foreach ($row as $key => $value) {
if (preg_match('/pass/i', $key)) {
unset($row[$key]);
}
}
}
return $row;
}
function getImageTransparent1pxURL() {
global $global;
return getCDN() . "view/img/transparent1px.png";
}
function getDatabaseTime() {
global $global, $_getDatabaseTime;
if (isset($_getDatabaseTime)) {
return $_getDatabaseTime;
}
$sql = "SELECT CURRENT_TIMESTAMP";
$res = sqlDAL::readSql($sql);
$data = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$row = $data;
} else {
$row = false;
}
$_getDatabaseTime = strtotime($row['CURRENT_TIMESTAMP']);
return $_getDatabaseTime;
}
function get_js_availableLangs() {
global $global;
if (empty($global['js_availableLangs'])) {
include_once $global['systemRootPath'] . 'objects/bcp47.php';
}
return $global['js_availableLangs'];
}
function listAllWordsToTranslate() {
global $global;
$cacheName = 'listAllWordsToTranslate';
$cache = ObjectYPT::getCache($cacheName, 0);
if (!empty($cache)) {
return object_to_array($cache);
}
ini_set('max_execution_time', 300);
function listAll($dir) {
$vars = array();
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$filename = $dir . "/" . $entry;
if (is_dir($filename)) {
$vars = listAll($filename);
} elseif (preg_match("/\.php$/", $entry)) {
$data = file_get_contents($filename);
$regex = '/__\(["\']{1}(.*)["\']{1}\)/U';
preg_match_all(
$regex,
$data,
$matches
);
foreach ($matches[0] as $key => $value) {
$vars[$matches[1][$key]] = $matches[1][$key];
}
}
}
}
closedir($handle);
}
return $vars;
}
$vars = listAll($global['systemRootPath']);
sort($vars);
ObjectYPT::setCache($cacheName, $vars);
return $vars;
}
function secondsInterval($time1, $time2) {
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
return $time1 - $time2;
}
function secondsIntervalHuman($time, $useDatabaseTime = true) {
$dif = secondsIntervalFromNow($time, $useDatabaseTime);
if ($dif < 0) {
return humanTimingAfterwards($time);
} else {
return humanTimingAgo($time);
}
}
function secondsIntervalFromNow($time, $useDatabaseTime = true) {
if ($useDatabaseTime) {
return secondsInterval(getDatabaseTime(), $time);
} else {
return secondsInterval(time(), $time);
}
}
function getScriptRunMicrotimeInSeconds() {
global $global;
$time_now = microtime(true);
return ($time_now - $global['avideoStartMicrotime']);
}
function fixSystemPath() {
global $global;
$global['systemRootPath'] = fixPath($global['systemRootPath']);
}
function fixPath($path, $addLastSlash = false) {
if (empty($path)) {
return false;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
} else {
$path = str_replace('\\', DIRECTORY_SEPARATOR, $path);
}
if ($addLastSlash) {
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
return $path;
}
function idToHash($id) {
global $global;
$id = base_convert($id, 10, 32);
$hash = (openssl_encrypt($id, 'rc4', $global['salt']));
//$hash = preg_replace('/^([+]+)/', '', $hash);
$hash = preg_replace('/(=+)$/', '', $hash);
$hash = str_replace(array('/', '+', '='), array('_', '-', '.'), $hash);
//return base64_encode($hash);
return $hash;
}
function hashToID($hash) {
global $global;
//$hash = str_pad($hash, 4, "=");
$hash = str_replace(array('_', '-', '.'), array('/', '+', '='), $hash);
//$hash = base64_decode($hash);
$decrypt = openssl_decrypt(($hash), 'rc4', $global['salt']);
$decrypt = base_convert($decrypt, 32, 10);
return intval($decrypt);
}
function videosHashToID($hash_of_videos_id) {
if (preg_match('/^\.([0-9a-z._-]+)/i', $hash_of_videos_id, $matches)) {
$hash_of_videos_id = hashToID($matches[1]);
}
return $hash_of_videos_id;
}
/**
*
* @global type $advancedCustom
* @global type $global
* @global type $_getCDNURL
* @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_FTP,CDN_YPTStorage,CDN_Live,CDN_LiveServers)
* @param type $id the ID of the URL in case the CDN is an array
* @return \type
*/
function getCDN($type = 'CDN', $id = 0) {
global $advancedCustom, $global, $_getCDNURL;
$index = $type . $id;
if (!isset($_getCDNURL)) {
$_getCDNURL = array();
}
if (empty($_getCDNURL[$index])) {
if (!empty($type) && AVideoPlugin::isEnabledByName('CDN')) {
$_getCDNURL[$index] = CDN::getURL($type, $id);
}
}
if ($type == 'CDN') {
if (!empty($global['ignoreCDN'])) {
return $global['webSiteRootURL'];
} else if (isValidURL($advancedCustom->videosCDN)) {
$_getCDNURL[$index] = addLastSlash($advancedCustom->videosCDN);
} else if (empty($_getCDNURL[$index])) {
$_getCDNURL[$index] = $global['webSiteRootURL'];
}
}
//var_dump($type, $id, $_getCDNURL[$index]);
return empty($_getCDNURL[$index]) ? false : $_getCDNURL[$index];
}
function getCDNOrURL($url, $type = 'CDN', $id = 0) {
$cdn = getCDN($type, $id);
if (!empty($cdn)) {
return $cdn;
}
return addLastSlash($url);
}
function isIPPrivate($ip) {
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
return false;
}
$result = filter_var(
$ip,
FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
if (empty($result)) {
return true;
}
return false;
}
function countDownPage($toTime, $message, $image, $bgImage) {
global $global;
include $global['systemRootPath'] . 'objects/functionCountDownPage.php';
exit;
}
+
+function login(){
+ $user = '';
+ $pass = '';
+ inputToRequest();
+ $scan = array('_POST', '_GET', '_REQUEST');
+ foreach ($scan as $value) {
+ $var = $$value;
+ if(empty($user) && !empty($var['user'])){
+ $user = $var['user'];
+ }
+ if(empty($pass) && !empty($var['pass'])){
+ $pass = $var['pass'];
+ }
+ }
+ User::loginFromRequest();
+}
+
+function inputToRequest(){
+ $content = json_decofile_get_contents("php://input");
+ if(!empty($content)){
+ $json = json_decode($content);
+ foreach ($json as $key => $value) {
+ if(!isset($_REQUEST[$key])){
+ $_REQUEST[$key] = $value;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/objects/user.php b/objects/user.php
index f09233231..b179ae882 100644
--- a/objects/user.php
+++ b/objects/user.php
@@ -1,2395 +1,2387 @@
user = $user;
if ($password !== false) {
$this->password = $password;
} else {
$this->loadFromUser($user);
}
} else {
// get data from id
$this->load($id);
}
}
public function getEmail() {
return $this->email;
}
public function getUser() {
return $this->user;
}
public function getAbout() {
return str_replace(array('\\\\\\\n'), array("\n"), $this->about);
}
public function setAbout($about) {
$this->about = xss_esc($about);
}
public function getPassword() {
return $this->password;
}
public function getCanStream() {
return $this->canStream;
}
public function setCanStream($canStream) {
$this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1;
}
public function getCanViewChart() {
return $this->canViewChart;
}
public function setCanViewChart($canViewChart) {
$this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1;
}
public function getCanCreateMeet() {
return $this->canCreateMeet;
}
public function setCanCreateMeet($canCreateMeet) {
$this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1;
;
}
public function getCanUpload() {
return $this->canUpload;
}
public function setCanUpload($canUpload) {
$this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1;
}
public function getAnalyticsCode() {
return $this->analyticsCode;
}
public function setAnalyticsCode($analyticsCode) {
preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches);
if (!empty($matches[1])) {
$this->analyticsCode = $matches[1];
} else {
$this->analyticsCode = "";
}
}
public function getAnalytics() {
$id = $this->getId();
$aCode = $this->getAnalyticsCode();
if (!empty($id) && !empty($aCode)) {
$code = "
";
} else {
$code = "";
}
return $code;
}
public function addExternalOptions($id, $value) {
$eo = unserialize(base64_decode($this->externalOptions));
if (!is_array($eo)) {
$eo = array();
}
$eo[$id] = $value;
$this->setExternalOptions($eo);
return $this->save();
}
public function removeExternalOptions($id) {
$eo = unserialize(base64_decode($this->externalOptions));
unset($eo[$id]);
$this->setExternalOptions($eo);
return $this->save();
}
public function setExternalOptions($options) {
//we convert it to base64 to sanitize the input since we do not validate input from externalOptions
$this->externalOptions = base64_encode(serialize($options));
}
public function getExternalOption($id) {
$eo = unserialize(base64_decode($this->externalOptions));
if (empty($eo[$id])) {
return null;
}
return $eo[$id];
}
private function load($id) {
$id = intval($id);
if (empty($id)) {
return false;
}
$user = self::getUserDb($id);
if (empty($user)) {
return false;
}
foreach ($user as $key => $value) {
$this->$key = $value;
}
return true;
}
private function loadFromUser($user) {
$userLoaded = self::getUserDbFromUser($user);
if (empty($userLoaded)) {
return false;
}
_error_log("User::loadFromUser($user) ");
_error_log("User::loadFromUser json " . json_encode(debug_backtrace()));
foreach ($userLoaded as $key => $value) {
$this->$key = $value;
}
return true;
}
public function loadSelfUser() {
$this->load($this->getId());
}
public static function getId() {
if (self::isLogged()) {
return $_SESSION['user']['id'];
} else {
return false;
}
}
public static function getEmail_() {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
public function getBdId() {
return $this->id;
}
public static function updateSessionInfo() {
if (self::isLogged()) {
$user = self::getUserDb($_SESSION['user']['id']);
$_SESSION['user'] = $user;
}
}
public static function getName() {
if (self::isLogged()) {
return $_SESSION['user']['name'];
} else {
return false;
}
}
public static function getUserName() {
if (self::isLogged()) {
return $_SESSION['user']['user'];
} else {
return false;
}
}
public static function getUserChannelName() {
if (self::isLogged()) {
if (empty($_SESSION['user']['channelName'])) {
$_SESSION['user']['channelName'] = self::_recommendChannelName();
$user = new User(User::getId());
$user->setChannelName($_SESSION['user']['channelName']);
$user->save();
}
return $_SESSION['user']['channelName'];
} else {
return false;
}
}
public static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) {
if (empty($users_id)) {
if (!empty(User::getId())) {
$users_id = User::getId();
}
}
if (empty($users_id)) {
$newChannelName = $name . "_" . uniqid();
if (strlen($newChannelName) > 40) {
$newChannelName = uniqid();
}
return $newChannelName;
}
if ($try > 10) {
_error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR);
return uniqid();
}
if (empty($name)) {
$name = self::getNameIdentification();
if ($name == __("Unknown User") && !empty($unknown)) {
$name = $unknown;
}
$name = cleanString($name);
}
// in case is a email get only the username
$parts = explode("@", $name);
$name = $parts[0];
// do not exceed 36 chars to leave some room for the unique id;
$name = substr($name, 0, 36);
if (!Permissions::canAdminUsers()) {
$user = self::getUserFromChannelName($name);
if ($user && $user['id'] !== $users_id) {
return self::_recommendChannelName($name . "_" . uniqid(), $try + 1);
}
}
return $name;
}
public static function getUserFromChannelName($channelName) {
$channelName = cleanString($channelName);
global $global;
$channelName = ($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
$user = cleanUpRowFromDatabase($user);
return $user;
} else {
return false;
}
}
/**
* return an name to identify the user
* @return String
*/
public static function getNameIdentification() {
global $advancedCustomUser;
if (self::isLogged()) {
if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) {
return self::getName();
}
if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return self::getMail();
}
if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return self::getUserName();
}
if (!empty(self::getUserChannelName())) {
return self::getUserChannelName();
}
}
return __("Unknown User");
}
/**
* return an name to identify the user from database
* @return String
*/
public function getNameIdentificationBd() {
global $advancedCustomUser;
if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) {
return $this->name;
}
if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return $this->email;
}
if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return $this->user;
}
if (!empty($this->channelName)) {
return $this->channelName;
}
return __("Unknown User");
}
public static function getNameIdentificationById($id = "") {
if (!empty($id)) {
$user = new User($id);
return $user->getNameIdentificationBd();
}
return __("Unknown User");
}
public static function getUserPass() {
if (self::isLogged()) {
return $_SESSION['user']['password'];
} else {
return false;
}
}
public function _getName() {
return $this->name;
}
public function getBdName() {
return $this->_getName();
}
public static function _getPhoto($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo)) {
if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) {
return $photo;
} else {
$photoPath = "/videos/userPhoto/photo{$id}.png";
$content = url_get_contents($photo);
file_put_contents($global['systemRootPath'] . $photoPath, $content);
$photo = $photoPath;
}
}
if (empty($photo)) {
$photo = "view/img/userSilhouette.jpg";
}
return $photo;
}
public static function getPhoto($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = getCDN() . $photo . "?" . filemtime($global['systemRootPath'] . $photo);
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = getCDN() . "view/img/userSilhouette.jpg";
}
return $photo;
}
public static function _getOGImage($users_id) {
return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg";
}
public static function deleteOGImage($users_id) {
global $global;
$photo = $global['systemRootPath'] . self::_getOGImage($users_id);
@unlink($photo);
}
public static function getOGImage($users_id = "") {
global $global;
$photo = self::_getPhoto($users_id);
if ($photo == "view/img/userSilhouette.jpg") {
return getCDN() . "view/img/userSilhouette.jpg";
}
if (empty($photo)) {
return false;
}
$source = $global['systemRootPath'] . $photo;
$destination = $global['systemRootPath'] . self::_getOGImage($users_id);
convertImageToOG($source, $destination);
return getCDN() . self::_getOGImage($users_id);
}
public static function getEmailVerifiedIcon($id = "") {
global $advancedCustomUser;
$mark = "";
if (!empty($advancedCustomUser->showEmailVerifiedMark)) {
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$verified = $user['emailVerified'];
}
} elseif (self::isLogged()) {
$verified = $_SESSION['user']['emailVerified'];
}
if (!empty($verified)) {
$mark .= ' ';
} else {
//return '';
$mark .= '';
}
}
if ($advancedCustomUser->Checkmark1Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark1")) {
$mark .= " " . $advancedCustomUser->Checkmark1HTML;
}
}
if ($advancedCustomUser->Checkmark2Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark2")) {
$mark .= " " . $advancedCustomUser->Checkmark2HTML;
}
}
if ($advancedCustomUser->Checkmark3Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark3")) {
$mark .= " " . $advancedCustomUser->Checkmark3HTML;
}
}
return $mark;
}
public function getPhotoDB() {
global $global;
$photo = self::getPhoto($this->id);
return $photo;
}
public static function getBackground($id = "") {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['backgroundURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['backgroundURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = getCDN() . $photo;
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = getCDN() . "view/img/background.png";
}
return $photo;
}
public static function getMail() {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
public function save($updateUserGroups = false) {
global $global, $config, $advancedCustom, $advancedCustomUser;
if (is_object($config) && $config->currentVersionLowerThen('5.6')) {
// they dont have analytics code
return false;
}
if (empty($this->user) || empty($this->password)) {
//echo "u:" . $this->user . "|p:" . strlen($this->password);
_error_log('Error : ' . __("You need a user and passsword to register"));
return false;
}
if (empty($this->isAdmin)) {
$this->isAdmin = "false";
}
if (empty($this->canStream)) {
if (empty($this->id)) { // it is a new user
if (empty($advancedCustomUser->newUsersCanStream)) {
$this->canStream = "0";
} else {
$this->canStream = "1";
}
} else {
$this->canStream = "0";
}
}
if (empty($this->canUpload)) {
$this->canUpload = "0";
}
if (empty($this->status)) {
$this->status = 'a';
}
if (empty($this->emailVerified)) {
$this->emailVerified = "false";
}
$user = ($this->user);
$password = ($this->password);
$name = ($this->name);
$status = ($this->status);
$this->about = preg_replace("/(\\\)+n/", "\n", $this->about);
$this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id);
$channelName = ($this->channelName);
if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) {
$this->donationLink = "";
}
if (!empty($this->id)) {
$formats = "ssssiiii";
$values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet);
$sql = "UPDATE users SET user = ?, password = ?, "
. "email = ?, name = ?, isAdmin = ?,"
. "canStream = ?,canUpload = ?,canCreateMeet = ?,";
if (isset($this->canViewChart)) {
$formats .= "i";
$values[] = $this->canViewChart;
$sql .= "canViewChart = ?, ";
}
$formats .= "ssssssissssssssssi";
$values[] = $this->status;
$values[] = $this->photoURL;
$values[] = $this->backgroundURL;
$values[] = $this->recoverPass;
$values[] = $this->about;
$values[] = $this->channelName;
$values[] = $this->emailVerified;
$values[] = $this->analyticsCode;
$values[] = $this->externalOptions;
$values[] = $this->first_name;
$values[] = $this->last_name;
$values[] = $this->address;
$values[] = $this->zip_code;
$values[] = $this->country;
$values[] = $this->region;
$values[] = $this->city;
$values[] = $this->donationLink;
$values[] = $this->id;
$sql .= "status = ?, "
. "photoURL = ?, backgroundURL = ?, "
. "recoverPass = ?, about = ?, "
. " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , "
. " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , "
. " modified = now() WHERE id = ?";
} else {
$formats = "ssssiiiissssss";
$values = array($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet,
$status, $this->photoURL, $this->recoverPass, $channelName, $this->analyticsCode, $this->externalOptions);
$sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) "
. " VALUES (?,?,?,?,?,?,?,?, false, "
. "?,?,?, now(), now(),?,?,?)";
}
$insert_row = sqlDAL::writeSql($sql, $formats, $values);
if ($insert_row) {
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
self::sendVerificationLink($id);
}
} else {
$id = $this->id;
}
if ($updateUserGroups) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
// update the user groups
UserGroups::updateUserGroups($id, $this->userGroups);
}
return $id;
} else {
_error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
return false;
}
}
public static function getChannelOwner($channelName) {
global $global;
$channelName = ($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$result = cleanUpRowFromDatabase($result);
$user = $result;
} else {
$user = false;
}
return $user;
}
public static function getFromUsername($user) {
global $global;
$user = ($user);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$result = cleanUpRowFromDatabase($result);
$user = $result;
} else {
$user = false;
}
return $user;
}
private static function setCacheWatchVideo($cacheName, $value) {
if (!User::isLogged()) {
ObjectYPT::setCache($cacheName, $value);
;
} else {
ObjectYPT::setSessionCache($cacheName, $value);
}
}
public static function canWatchVideo($videos_id) {
$cacheName = "canWatchVideo$videos_id";
if (!User::isLogged()) {
$cacheName = "canWatchVideoNOTLOGED$videos_id";
$cache = ObjectYPT::getCache($cacheName, 3600);
} else {
$cache = ObjectYPT::getSessionCache($cacheName, 600);
}
if (isset($cache)) {
if($cache === 'false'){
$cache = false;
}
return $cache;
}
if (empty($videos_id)) {
_error_log("User::canWatchVideo Video is empty ({$videos_id})");
return false;
}
if (User::isAdmin()) {
return true;
}
$video = new Video("", "", $videos_id);
if ($video->getStatus() === 'i') {
_error_log("User::canWatchVideo Video is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
$user = new User($video->getUsers_id());
if ($user->getStatus() === 'i') {
_error_log("User::canWatchVideo User is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
// check if any plugin restrict access to this video
if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
if (User::isLogged()) {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})");
} else {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})");
}
self::setCacheWatchVideo($cacheName, false);
return false;
} else {
self::setCacheWatchVideo($cacheName, true);
return true; // the video is public
}
}
if (!User::isLogged()) {
_error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr());
self::setCacheWatchVideo($cacheName, false);
return false;
}
// if is not public check if the user is on one of its groups
$rowsUser = UserGroups::getUserGroups(User::getId());
foreach ($rows as $value) {
foreach ($rowsUser as $value2) {
if ($value['id'] === $value2['id']) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
}
}
_error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows));
self::setCacheWatchVideo($cacheName, false);
return false;
}
public static function canWatchVideoWithAds($videos_id) {
if (empty($videos_id)) {
_error_log("User::canWatchVideo (videos_id is empty) " . $videos_id);
return false;
}
if (User::isAdmin()) {
return true;
}
if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) {
//_error_log("User::userCanWatchVideoWithAds (can) " . User::getId() . " " . $videos_id);
return true;
}
_error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id);
if (self::canWatchVideo($videos_id)) {
//_error_log("User::canWatchVideo (can) " . $videos_id);
return true;
}
_error_log("User::canWatchVideo (No can not) " . $videos_id);
return false;
}
public function delete() {
if (!self::isAdmin()) {
return false;
}
// cannot delete yourself
if (self::getId() === $this->id) {
return false;
}
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM users WHERE id = ?";
} else {
return false;
}
return sqlDAL::writeSql($sql, "i", array($this->id));
}
const USER_LOGGED = 0;
const USER_NOT_VERIFIED = 1;
const USER_NOT_FOUND = 2;
const CAPTCHA_ERROR = 3;
const REQUIRE2FA = 4;
public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = false) {
if (User::isLogged()) {
return false;
}
global $global, $advancedCustom, $advancedCustomUser, $config;
if (strtolower($encodedPass) === 'false') {
$encodedPass = false;
}
//_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr());
if ($noPass) {
$user = $this->find($this->user, false, true);
} else {
$user = $this->find($this->user, $this->password, true, $encodedPass);
}
if (!self::checkLoginAttempts()) {
return self::CAPTCHA_ERROR;
}
ObjectYPT::clearSessionCache();
_session_start();
// check for multiple logins attempts to prevent hacking end
// if user is not verified
if (empty($ignoreEmailVerification) && !empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
unset($_SESSION['user']);
self::sendVerificationLink($user['id']);
return self::USER_NOT_VERIFIED;
} elseif ($user) {
$_SESSION['user'] = $user;
$this->setLastLogin($_SESSION['user']['id']);
$rememberme = 0;
if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) {
$expires = strtotime("+ 1 year");
$rememberme = 1;
} else {
$expires = 0;
}
_setcookie("rememberme", $rememberme, $expires);
_setcookie("user", $user['user'], $expires);
_setcookie("pass", $user['password'], $expires);
AVideoPlugin::onUserSignIn($_SESSION['user']['id']);
$_SESSION['loginAttempts'] = 0;
session_write_close();
return self::USER_LOGGED;
} else {
unset($_SESSION['user']);
return self::USER_NOT_FOUND;
}
}
public static function isCaptchaNeed() {
global $advancedCustomUser;
// check for multiple logins attempts to prevent hacking
if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
if (isMobile()) {
$advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10;
}
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
return true;
}
}
return false;
}
public static function checkLoginAttempts() {
global $advancedCustomUser, $global;
// check for multiple logins attempts to prevent hacking
if (empty($_SESSION['loginAttempts'])) {
_session_start();
$_SESSION['loginAttempts'] = 0;
}
if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
_session_start();
$_SESSION['loginAttempts']++;
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
if (empty($_POST['captcha'])) {
return false;
}
require_once $global['systemRootPath'] . 'objects/captcha.php';
if (!Captcha::validation($_POST['captcha'])) {
return false;
}
}
}
return true;
}
public static function getCaptchaFormIfNeed() {
// check for multiple logins attempts to prevent hacking
if (self::isCaptchaNeed()) {
return self::getCaptchaForm();
}
return "";
}
public static function getCaptchaForm($uid = "") {
global $global;
return '
';
}
private function setLastLogin($user_id) {
global $global;
if (empty($user_id)) {
die('Error : setLastLogin ');
}
$sql = "UPDATE users SET lastLogin = now(), modified = now() WHERE id = ?";
return sqlDAL::writeSql($sql, "i", array($user_id));
}
public static function logoff() {
global $global, $justLogoff;
$justLogoff = true;
_session_start();
ObjectYPT::deleteAllSessionCache();
_unsetcookie('rememberme');
_unsetcookie('user');
_unsetcookie('pass');
unset($_SESSION['user']);
}
private static function recreateLoginFromCookie() {
global $justLogoff, $justTryToRecreateLoginFromCookie;
if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) {
$justTryToRecreateLoginFromCookie = 1;
// first check if the LoginControl::singleDeviceLogin is enabled, if it is only recreate login if the device is the last device
if ($obj = AVideoPlugin::getDataObjectIfEnabled("LoginControl")) {
if (!empty($obj->singleDeviceLogin)) {
if (!LoginControl::isLoggedFromSameDevice()) {
_error_log("user::recreateLoginFromCookie: LoginControl and the last logged device is different: " . $_COOKIE['user'] . "");
self::logoff();
return false;
}
}
}
if ((!empty($_COOKIE['user'])) && (!empty($_COOKIE['pass'])) && (!empty($_COOKIE['rememberme']))) {
$user = new User(0, $_COOKIE['user'], false);
$user->setPassword($_COOKIE['pass'], true);
// $dbuser = self::getUserDbFromUser($_COOKIE['user']);
$resp = $user->login(false, true);
_error_log("user::recreateLoginFromCookie: do cookie-login: " . $_COOKIE['user'] . " result: " . $resp);
if (0 == $resp) {
_error_log("success " . $_SESSION['user']['id']);
} else {
_error_log("user::recreateLoginFromCookie: do logoff: " . $_COOKIE['user'] . " result: " . $resp);
self::logoff();
}
}
}
}
public static function isLogged() {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['id']);
}
public static function isVerified() {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['emailVerified']);
}
public static function isAdmin() {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['isAdmin']);
}
public static function canStream() {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']);
}
public static function externalOptions($id) {
if (!empty($_SESSION['user']['externalOptions'])) {
$externalOptions = unserialize(base64_decode($_SESSION['user']['externalOptions']));
if (isset($externalOptions[$id])) {
if ($externalOptions[$id] == "true") {
$externalOptions[$id] = true;
} elseif ($externalOptions[$id] == "false") {
$externalOptions[$id] = false;
}
return $externalOptions[$id];
}
}
return false;
}
public static function externalOptionsFromUserID($users_id, $id) {
$user = self::findById($users_id);
if ($user) {
if (!is_null($user['externalOptions'])) {
$externalOptions = unserialize(base64_decode($user['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
if ($id != $k) {
continue;
}
if ($v == "true") {
$v = 1;
} elseif ($v == "false") {
$v = 0;
}
return $v;
}
}
}
}
return false;
}
public function thisUserCanStream() {
if ($this->status === 'i') {
return false;
}
return !empty($this->isAdmin) || !empty($this->canStream);
}
private function find($user, $pass, $mustBeactive = false, $encodedPass = false) {
global $global, $advancedCustom;
$formats = "";
$values = array();
$sql = "SELECT * FROM users WHERE user = ? ";
$formats .= "s";
$values[] = $user;
if ($mustBeactive) {
$sql .= " AND status = 'a' ";
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, $formats, $values, true);
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($result)) {
if ($pass !== false) {
if (!encryptPasswordVerify($pass, $result['password'], $encodedPass)) {
if (!empty($advancedCustom) && $advancedCustom->enableOldPassHashCheck) {
_error_log("Password check new hash pass does not match, trying MD5");
return $this->find_Old($user, $pass, $mustBeactive, $encodedPass);
} else {
return false;
}
}
}
$user = $result;
} else {
_error_log("Password check new hash user not found");
//check if is the old password style
$user = false;
//$user = false;
}
return $user;
}
/**
* this is the deprecated function, with week password
* @global type $global
* @param type $user
* @param type $pass
* @param type $mustBeactive
* @param type $encodedPass
* @return boolean
*/
private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false) {
global $global;
$formats = "";
$values = array();
$sql = "SELECT * FROM users WHERE user = ? ";
$formats .= "s";
$values[] = $user;
if ($mustBeactive) {
$sql .= " AND status = 'a' ";
}
if ($pass !== false) {
if (!$encodedPass || $encodedPass === 'false') {
_error_log("Password check Old not encoded pass");
$passEncoded = md5($pass);
} else {
_error_log("Password check Old encoded pass");
$passEncoded = $pass;
}
$sql .= " AND password = ? ";
$formats .= "s";
$values[] = $passEncoded;
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, $formats, $values, true);
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($result)) {
if (!$encodedPass || $encodedPass === 'false') {
//update the password
$u = new User($result['id']);
$u->setPassword($pass);
$u->save();
$result['password'] = $u->getPassword();
}
$user = $result;
} else {
$user = false;
}
if (empty($user)) {
_error_log("Password check Old not found");
} else {
_error_log("Password check Old found");
}
return $user;
}
private static function findById($id) {
global $global;
$id = intval($id);
if (empty($id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($id));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$user = $result;
} else {
$user = false;
}
return $user;
}
public static function findByEmail($email) {
global $global;
$email = trim($email);
if (empty($email)) {
return false;
}
$sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($email));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $result;
} else {
$user = false;
}
return $user;
}
private static function getUserDb($id) {
global $global;
$id = intval($id);
if (empty($id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1;";
$res = sqlDAL::readSql($sql, "i", array($id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
private static function getUserDbFromUser($user) {
global $global;
if (empty($user)) {
return false;
}
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
public static function getUserFromID($users_id) {
global $global;
if (empty($users_id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($users_id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
$user['groups'] = UserGroups::getUserGroups($user['id']);
$user['identification'] = self::getNameIdentificationById($user['id']);
$user['photo'] = self::getPhoto($user['id']);
$user['background'] = self::getBackground($user['id']);
$user['tags'] = self::getTags($user['id']);
$user['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $user['name']);
$user['isEmailVerified'] = $user['emailVerified'];
if (!is_null($user['externalOptions'])) {
$externalOptions = unserialize(base64_decode($user['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
if ($v == "true") {
$v = 1;
} elseif ($v == "false") {
$v = 0;
}
$user[$k] = $v;
}
}
}
unset($user['password']);
unset($user['recoverPass']);
if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) {
unset($user['first_name']);
unset($user['last_name']);
unset($user['address']);
unset($user['zip_code']);
unset($user['country']);
unset($user['region']);
unset($user['city']);
}
$user = $user;
return $user;
}
return false;
}
public static function getUserFromEmail($email) {
$email = trim($email);
$sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($email));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
public function setUser($user) {
global $advancedCustomUser;
if (empty($advancedCustomUser->userCanChangeUsername)) {
if (!empty($this->user)) {
return false;
}
}
$this->user = strip_tags($user);
}
public function setName($name) {
$this->name = strip_tags($name);
}
public function setEmail($email) {
global $advancedCustomUser;
$email = strip_tags($email);
if (!empty($advancedCustomUser->emailMustBeUnique)) {
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
$userFromEmail = User::getUserFromEmail($email);
if (!empty($userFromEmail)) {
return false;
}
}
$this->email = $email;
return true;
}
public function setPassword($password, $doNotEncrypt = false) {
if (!empty($password)) {
if ($doNotEncrypt) {
$this->password = ($password);
} else {
$this->password = encryptPassword($password);
}
}
}
public function setIsAdmin($isAdmin) {
if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) {
$isAdmin = "0";
} else {
$isAdmin = "1";
}
$this->isAdmin = $isAdmin;
}
public function setStatus($status) {
$this->status = strip_tags($status);
}
public function getPhotoURL() {
return $this->photoURL;
}
public function setPhotoURL($photoURL) {
$this->photoURL = strip_tags($photoURL);
}
public static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
$users_groups_id = intval($users_groups_id);
if (empty($users_groups_id)) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT * FROM users u WHERE 1=1 ";
$sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) ";
$ids = AVideoPlugin::getDynamicUsersId($users_groups_id);
if(!empty($ids) && is_array($ids)){
$ids = array_unique($ids);
$sql .= " OR id IN ('". implode("','", $ids)."') ";
}
$sql .= " ) ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND u.status = 'i' ";
} else {
$sql .= " AND u.status = 'a' ";
}
}
$sql .= BootGrid::getSqlFromPost($searchFields);
$user = array();
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$row = cleanUpRowFromDatabase($row);
$user[] = self::getUserInfoFromRow($row);
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
public static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "") {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
$users_groups_id = intval($users_groups_id);
if (empty($users_groups_id)) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT id FROM users WHERE 1=1 ";
$sql .= " AND (id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) ";
$ids = AVideoPlugin::getDynamicUsersId($users_groups_id);
if(!empty($ids) && is_array($ids)){
$ids = array_unique($ids);
$sql .= " OR id IN ('". implode("','", $ids)."') ";
}
$sql .= " ) ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user'));
$res = sqlDAL::readSql($sql);
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
return $result;
}
public static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT * FROM users WHERE 1=1 ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlFromPost($searchFields);
$user = array();
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$row = cleanUpRowFromDatabase($row);
$user[] = self::getUserInfoFromRow($row);
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
public static function getAllActiveUsersThatCanUpload() {
if (!Permissions::canAdminUsers()) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT * FROM users WHERE 1=1 AND status = 'a' AND (canUpload = 1 OR isAdmin = 1) ";
$user = array();
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$row = cleanUpRowFromDatabase($row);
$user[] = $row;
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
private static function getUserInfoFromRow($row) {
$row['groups'] = UserGroups::getUserGroups($row['id']);
$row['identification'] = self::getNameIdentificationById($row['id']);
$row['photo'] = self::getPhoto($row['id']);
$row['background'] = self::getBackground($row['id']);
$row['tags'] = self::getTags($row['id']);
$row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']);
$row['isEmailVerified'] = $row['emailVerified'];
if (!is_null($row['externalOptions'])) {
$externalOptions = unserialize(base64_decode($row['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
if ($v == "true") {
$v = 1;
} elseif ($v == "false") {
$v = 0;
}
$row[$k] = $v;
}
}
}
unset($row['password']);
unset($row['recoverPass']);
if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) {
unset($row['first_name']);
unset($row['last_name']);
unset($row['address']);
unset($row['zip_code']);
unset($row['country']);
unset($row['region']);
unset($row['city']);
}
return $row;
}
public static function getAllUsersThatHasVideos($ignoreAdmin = false) {
if (!self::isAdmin() && !$ignoreAdmin) {
return false;
}
global $global;
$sql = "SELECT * FROM users u WHERE status = 'a' AND (canUpload = 1 || isAdmin = 1) AND "
. " (SELECT count(id) FROM videos where users_id = u.id )>0 ";
$user = array();
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$row = cleanUpRowFromDatabase($row);
$user[] = $row;
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
public static function getTotalUsers($ignoreAdmin = false, $status = "") {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT id FROM users WHERE 1=1 ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user'));
$res = sqlDAL::readSql($sql);
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
return $result;
}
public static function userExists($user) {
global $global;
$user = ($user);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user['id'];
} else {
return false;
}
}
public static function idExists($users_id) {
global $global;
$users_id = intval($users_id);
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($users_id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user['id'];
} else {
return false;
}
}
public static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) {
global $global, $advancedCustomUser;
$userId = 0;
if (!$userId = self::userExists($user)) {
if (empty($pass)) {
$pass = uniqid();
}
$pass = encryptPassword($pass);
$userObject = new User(0, $user, $pass);
$userObject->setEmail($email);
$userObject->setName($name);
$userObject->setIsAdmin($isAdmin);
$userObject->setPhotoURL($photoURL);
$userObject->setEmailVerified($emailVerified);
$userId = $userObject->save();
if (!empty($userId)) {
if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup
UserGroups::updateUserGroups($userId, array($advancedCustomUser->userDefaultUserGroup->value), true);
}
}
return $userId;
} else {
if ($emailVerified) {
$userObj = new User($userId);
if (!$userObj->getEmailVerified()) {
$userObj->setEmailVerified(1);
$userObj->save();
}
}
}
return $userId;
}
public function getRecoverPass() {
return $this->recoverPass;
}
public function setRecoverPass($forceChange = false) {
// let the same recover pass if it was 10 minutes ago
if (!$this->isRecoverPassExpired($this->recoverPass) && empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) {
return $this->recoverPass;
}
$this->recoverPass = $this->createRecoverPass();
return $this->recoverPass;
}
private function createRecoverPass($secondsValid = 600) {
$json = new stdClass();
$json->valid = strtotime("+{$secondsValid} seconds");
return encryptString(json_encode($json));
}
function checkRecoverPass($recoverPass) {
if ($this->recoverPass === $recoverPass) {
if (!$this->isRecoverPassExpired($recoverPass)) {
_error_log('checkRecoverPass success: ' . $this->user . ' ' . getRealIpAddr());
return true;
}
}
return false;
}
function isRecoverPassExpired($recoverPass) {
$string = decryptString($recoverPass);
if ($string) {
$json = _json_decode($string);
if (is_object($json)) {
if (time() < $json->valid) {
return false;
}
}
}
return true;
}
public static function canUpload($doNotCheckPlugins = false) {
global $global, $config, $advancedCustomUser;
if (Permissions::canModerateVideos()) {
return true;
}
if (User::isAdmin()) {
return true;
}
if (empty($doNotCheckPlugins) && !AVideoPlugin::userCanUpload(User::getId())) {
return false;
}
if (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && !User::isVerified()) {
return false;
}
if ($config->getAuthCanUploadVideos()) {
return self::isLogged();
}
if (self::isLogged() && !empty($_SESSION['user']['canUpload'])) {
return true;
}
return self::isAdmin();
}
public static function canViewChart() {
global $global, $config;
if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) {
return true;
}
return self::isAdmin();
}
public static function canCreateMeet() {
global $global, $config;
if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) {
return true;
}
return self::isAdmin();
}
public static function canComment() {
global $global, $config, $advancedCustomUser;
if (self::isAdmin()) {
return true;
}
if (Permissions::canAdminComment()) {
return true;
}
if ($config->getAuthCanComment()) {
if (empty($advancedCustomUser->unverifiedEmailsCanNOTComment)) {
return self::isLogged();
} else {
return self::isVerified();
}
}
return false;
}
public static function canSeeCommentTextarea() {
global $global, $config;
if (!$config->getAuthCanComment()) {
if (!self::isAdmin()) {
return false;
}
}
return true;
}
public function getUserGroups() {
return $this->userGroups;
}
public function setUserGroups($userGroups) {
if (is_array($userGroups)) {
$this->userGroups = $userGroups;
}
}
public function getIsAdmin() {
return $this->isAdmin;
}
public function getStatus() {
return $this->status;
}
/**
*
* @param type $user_id
* text
* label Default Primary Success Info Warning Danger
*/
public static function getTags($user_id) {
$user = new User($user_id);
$tags = array();
if ($user->getIsAdmin()) {
$obj = new stdClass();
$obj->type = "info";
$obj->text = __("Admin");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "default";
$obj->text = __("Regular User");
$tags[] = $obj;
}
if ($user->getStatus() == "a") {
$obj = new stdClass();
$obj->type = "success";
$obj->text = __("Active");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "danger";
$obj->text = __("Inactive");
$tags[] = $obj;
}
if ($user->getEmailVerified()) {
$obj = new stdClass();
$obj->type = "success";
$obj->text = __("E-mail Verified");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "warning";
$obj->text = __("E-mail Not Verified");
$tags[] = $obj;
}
global $global;
if (!empty($global['systemRootPath'])) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
} else {
require_once 'userGroups.php';
}
$groups = UserGroups::getUserGroups($user_id);
foreach ($groups as $value) {
$obj = new stdClass();
$obj->type = "warning";
$obj->text = $value['group_name'];
$tags[] = $obj;
}
return $tags;
}
public function getBackgroundURL() {
global $global;
$this->backgroundURL = self::getBackgroundURLFromUserID($this->id);
return $this->backgroundURL;
}
public static function getBackgroundURLFromUserID($users_id = 0) {
if (empty($users_id)) {
$users_id = User::getId();
}
global $global;
$backgroundURL = "videos/userPhoto/background{$users_id}.jpg";
if (!file_exists($global['systemRootPath'] . $backgroundURL)) {
$backgroundURL = "videos/userPhoto/background{$users_id}.png";
}
if (!file_exists($global['systemRootPath'] . $backgroundURL)) {
$backgroundURL = "view/img/background.jpg";
}
return $backgroundURL;
}
public function setBackgroundURL($backgroundURL) {
$this->backgroundURL = strip_tags($backgroundURL);
}
public function getChannelName() {
if (empty($this->channelName)) {
$this->channelName = self::_recommendChannelName($this->channelName);
$this->save();
}
return $this->channelName;
}
public static function _getUserChannelName($users_id = 0) {
global $global, $config;
if (empty($users_id)) {
$users_id = self::getId();
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
return $user->getChannelName();
}
public function getEmailVerified() {
return intval($this->emailVerified);
}
public static function validateChannelName($channelName) {
return trim(preg_replace("/[^0-9A-Z_]/i", "", ucwords($channelName)));
}
/**
*
* @param type $channelName
* @return boolean return true is is unique
*/
public function setChannelName($channelName) {
$channelName = self::validateChannelName($channelName);
$user = static::getChannelOwner($channelName);
if (!empty($user)) { // if the channel name exists and it is not from this user, rename the channel name
if (empty($this->id) || $user['id'] != $this->id) {
return false;
}
}
$this->channelName = xss_esc($channelName);
return true;
}
public function setEmailVerified($emailVerified) {
$this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1;
}
public static function getChannelLink($users_id = 0) {
global $global;
$name = self::_getChannelName($users_id);
if (empty($name)) {
return false;
}
$link = "{$global['webSiteRootURL']}channel/" . urlencode($name);
return $link;
}
public static function getChannelLinkFromChannelName($channelName) {
global $global;
$link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName);
return $link;
}
public static function _getChannelName($users_id = 0) {
global $global, $config;
if (empty($users_id)) {
$users_id = self::getId();
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
if (empty($user->getChannelName())) {
$name = $user->getBdId();
} else {
$name = $user->getChannelName();
}
return $name;
}
public static function sendVerificationLink($users_id) {
global $global, $advancedCustomUser;
//Only send the verification email each 30 minutes
if (!empty($_SESSION["sendVerificationLink"][$users_id]) && time() - $_SESSION["sendVerificationLink"][$users_id] > 1800) {
_error_log("sendVerificationLink: Email already sent, we will wait 30 min {$users_id}");
return true;
}
$config = new Configuration();
$user = new User($users_id);
$code = urlencode(static::createVerificationCode($users_id));
//Create a new PHPMailer instance
if (!is_object($config)) {
_error_log("sendVerificationLink: config is not a object " . json_encode($config));
return false;
}
$contactEmail = $config->getContactEmail();
$webSiteTitle = $config->getWebSiteTitle();
$email = $user->getEmail();
try {
$mail = new \PHPMailer\PHPMailer\PHPMailer;
setSiteSendMessage($mail);
//$mail->SMTPDebug = 4;
//Set who the message is to be sent from
$mail->setFrom($contactEmail, $webSiteTitle);
//Set who the message is to be sent to
$mail->addAddress($email);
//Set the subject line
$mail->Subject = __('Please Verify Your E-mail ') . $webSiteTitle;
$msg = sprintf(__("Hi %s"), $user->getName());
$msg .= "
" . __($advancedCustomUser->verificationMailTextLine1);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine2), $webSiteTitle);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine3), $webSiteTitle);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine4));
$msg .= "
" . " " . __("Verify") . "";
$mail->msgHTML($msg);
$resp = $mail->send();
if (!$resp) {
_error_log("sendVerificationLink Error Info: {$mail->ErrorInfo}");
} else {
_session_start();
$_SESSION["sendVerificationLink"][$users_id] = time();
}
return $resp;
} catch (phpmailerException $e) {
_error_log($e->errorMessage()); //Pretty error messages from PHPMailer
} catch (Exception $e) {
_error_log($e->getMessage()); //Boring error messages from anything else!
}
return false;
}
public static function verifyCode($code) {
global $global;
$obj = static::decodeVerificationCode($code);
$salt = hash('sha256', $global['salt']);
if ($salt !== $obj->salt) {
return false;
}
$user = new User($obj->users_id);
$recoverPass = $user->getRecoverPass();
if ($recoverPass == $obj->recoverPass) {
$user->setEmailVerified(1);
return $user->save();
}
return false;
}
public static function createVerificationCode($users_id) {
global $global;
$obj = new stdClass();
$obj->users_id = $users_id;
$obj->salt = hash('sha256', $global['salt']);
$user = new User($users_id);
$obj->recoverPass = $user->setRecoverPass();
$user->save();
return base64_encode(json_encode($obj));
}
public static function decodeVerificationCode($code) {
$obj = _json_decode(base64_decode($code));
return $obj;
}
public function getFirst_name() {
return $this->first_name;
}
public function getLast_name() {
return $this->last_name;
}
public function getAddress() {
return $this->address;
}
public function getZip_code() {
return $this->zip_code;
}
public function getCountry() {
return $this->country;
}
public function getRegion() {
return $this->region;
}
public function getCity() {
return $this->city;
}
public function setFirst_name($first_name) {
$this->first_name = $first_name;
}
public function setLast_name($last_name) {
$this->last_name = $last_name;
}
public function setAddress($address) {
$this->address = $address;
}
public function setZip_code($zip_code) {
$this->zip_code = $zip_code;
}
public function setCountry($country) {
$this->country = $country;
}
public function setRegion($region) {
$this->region = $region;
}
public function setCity($city) {
$this->city = $city;
}
public static function getDocumentImage($users_id) {
$row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE);
if (!empty($row['blob'])) {
return $row['blob'];
}
return false;
}
public static function saveDocumentImage($image, $users_id) {
$row = static::saveBlob($image, $users_id, User::$DOCUMENT_IMAGE_TYPE);
if (!empty($row['blob'])) {
return $row['blob'];
}
return false;
}
public static function getBlob($users_id, $type) {
global $global;
$sql = "SELECT * FROM users_blob WHERE users_id = ? AND `type` = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "is", array($users_id, $type));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $result;
}
public static function saveBlob($blob, $users_id, $type) {
global $global;
$row = self::getBlob($users_id, $type);
$null = null;
if (!empty($row['id'])) {
$sql = "UPDATE users_blob SET `blob` = ? , modified = now() WHERE id = ?";
$stmt = $global['mysqli']->prepare($sql);
$stmt->bind_param('bi', $null, $row['id']);
} else {
$sql = "INSERT INTO users_blob (`blob`, users_id, `type`, modified, created) VALUES (?,?,?, now(), now())";
$stmt = $global['mysqli']->prepare($sql);
$stmt->bind_param('bis', $null, $users_id, $type);
}
$stmt->send_long_data(0, $blob);
return $stmt->execute();
}
public static function deleteBlob($users_id, $type) {
global $global;
$row = self::getBlob($users_id, $type);
if (!empty($row['id'])) {
$sql = "DELETE FROM users_blob ";
$sql .= " WHERE id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($row['id']));
}
_error_log("Id for table users_blob not defined for deletion");
return false;
}
public function getDonationLink() {
return $this->donationLink;
}
public function getDonationLinkIfEnabled() {
global $advancedCustomUser;
if ($advancedCustomUser->allowDonationLink) {
return $this->donationLink;
}
return false;
}
public function setDonationLink($donationLink) {
$this->donationLink = $donationLink;
}
public static function donationLink() {
if (self::isLogged()) {
return $_SESSION['user']['donationLink'];
} else {
return false;
}
}
public static function loginFromRequest() {
- $inputJSON = url_get_contents('php://input');
- $input = _json_decode($inputJSON, true); //convert JSON into array
- if (is_array($input)) {
- foreach ($input as $key => $value) {
- if (empty($_REQUEST[$key])) {
- $_REQUEST[$key] = $value;
- }
- }
- }
+ inputToRequest();
if (!empty($_REQUEST['do_not_login'])) {
return false;
}
if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) {
$user = new User(0, $_REQUEST['user'], $_REQUEST['pass']);
$user->login(false, !empty($_REQUEST['encodedPass']));
}
}
public static function loginFromRequestToGet() {
if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) {
$return = "user={$_REQUEST['user']}&pass={$_REQUEST['pass']}";
if (!empty($_REQUEST['encodedPass'])) {
$return .= "&encodedPass=" . intval($_REQUEST['encodedPass']);
}
return $return;
}
return "";
}
public static function getBlockUserButton($users_id) {
$canBlock = self::userCanBlockUserWithReason($users_id);
if (!$canBlock->result) {
return "";
}
return ReportVideo::buttonBlockUser($users_id);
}
public static function getActionBlockUserButton($users_id) {
$canBlock = self::userCanBlockUserWithReason($users_id);
if (!$canBlock->result) {
return "";
}
return ReportVideo::actionButtonBlockUser($users_id);
}
public static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false) {
if (empty($users_id)) {
return false;
}
if (!User::isLogged()) {
return false;
}
if ($users_id == User::getId()) {
return false;
}
if (empty($ignoreIfIsAlreadyBLocked)) {
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (empty($report)) {
return false;
}
}
return true;
}
public static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false) {
$obj = new stdClass();
$obj->result = false;
$obj->msg = "Unkonw";
if (empty($users_id)) {
$obj->msg = "Empty User ID";
return $obj;
}
if (!User::isLogged()) {
$obj->msg = "You are not logged";
return $obj;
}
if ($users_id == User::getId()) {
$obj->msg = "You cannot block your own video";
return $obj;
}
if (empty($ignoreIfIsAlreadyBLocked)) {
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (empty($report)) {
$obj->msg = "this user is already blocked";
return $obj;
}
}
$obj->result = true;
$obj->msg = "You can block";
return $obj;
}
public static function hasBlockedUser($reported_users_id, $users_id = 0) {
if (empty($users_id)) {
$users_id = User::getId();
}
if (!self::userCanBlockUser($reported_users_id, true)) {
return false;
}
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (!empty($report)) {
return ReportVideo::isBlocked($reported_users_id, $users_id);
} else {
return false;
}
}
public function updateUserImages($params = array()) {
$id = $this->id;
$obj = new stdClass();
// Update Background Image
if (isset($params['backgroundImg']) && $params['backgroundImg'] != '') {
$background = url_get_contents($params['backgroundImg']);
$ext = pathinfo(parse_url($params['backgroundImg'], PHP_URL_PATH), PATHINFO_EXTENSION);
$allowed = array('jpg', 'jpeg', 'gif', 'png');
if (!in_array(strtolower($ext), $allowed)) {
return "File extension error background Image, We allow only (" . implode(",", $allowed) . ")";
}
$backgroundPath = "videos/userPhoto/tmp_background{$id}." . $ext;
$oldfile = "videos/userPhoto/background{$id}.png";
$file = "videos/userPhoto/background{$id}.jpg";
if (!isset($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
$filePath = $global['systemRootPath'] . $backgroundPath;
$updateBackground = file_put_contents($filePath, $background);
convertImage($filePath, $global['systemRootPath'] . $file, 70);
if (file_exists($filePath)) {
unlink($filePath);
}
if (file_exists($oldfile)) {
unlink($oldfile);
}
if ($updateBackground) {
$obj->background = 'Background has been updated!';
} else {
$obj->background = 'Error updating background.';
}
$this->setBackgroundURL($file);
}
// Update Profile Image
if (isset($params['profileImg']) && $params['profileImg'] != '') {
$photo = url_get_contents($params['profileImg']);
$photoPath = "videos/userPhoto/photo{$id}.png";
if (!isset($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
$filePath = $global['systemRootPath'] . $photoPath;
if (file_exists($filePath)) {
unlink($filePath);
}
$updateProfile = file_put_contents($filePath, $photo);
if ($updateProfile) {
$obj->profile = 'Profile has been updated!';
} else {
$obj->profile = 'Error updating profile.';
}
$this->setPhotoURL($photoPath);
}
$formats = "ssi";
$values[] = $this->photoURL;
$values[] = $this->backgroundURL;
$values[] = $this->id;
$sql = "UPDATE users SET "
. "photoURL = ?, backgroundURL = ?, "
. " modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, $formats, $values);
$obj->save = $insert_row; // create/update data for photoURL / backgroundURL
return $obj;
}
function getExtra_info() {
return $this->extra_info;
}
function setExtra_info($extra_info) {
$this->extra_info = $extra_info;
}
static function saveExtraInfo($string, $users_id) {
$sql = "UPDATE users SET "
. "extra_info = ?, "
. " modified = now() WHERE id = ?";
return sqlDAL::writeSql($sql, "si", array($string, $users_id));
}
static function userGroupsMatch($user_groups, $users_id=0){
if(empty($users_id)){
$users_id = User::getId();
}
if(empty($user_groups)){
return true;
}
if(empty($users_id)){
return false;
}
if(!is_array($user_groups)){
$user_groups = array($user_groups);
}
$user_users_groups = UserGroups::getUserGroups($users_id);
if(empty($user_users_groups)){
return false;
}
foreach ($user_users_groups as $value) {
if(in_array($value['id'], $user_groups)){
return true;
}
}
return false;
}
}